how to handle request method from go. I don't use libraries

Issue

before that I worked with node js and it was easy to understand how to handle methods

example on node js:

    switch (request.method) {

    case 'OPTIONS': return OptionsResponse(response);
    case 'GET': return GetSwitch(request, response);
    case 'POST': return PostSwitch(request, response);
    case 'PUT': return PutSwitch(request, response);
    case 'DELETE': return DeleteSwitch(request, response);
    default: return ErrorMessage( "Sorry, this method not supported", 501, request);

}

but in go i can’t figure out how to do it

package utils

import (

    "log"
    "net/http"

    "github.com/user/go_rest_api/src/view" // page view

    "github.com/user/go_rest_api/src/api" // only api server
);

How can I implement the same handler in go?

func HandlerRequestFunc() {

http.HandleFunc("/", view.Homepage);

/*get method from api server */
http.HandleFunc("/api", api.InfoFromApi);

/* from db api handler */
http.HandleFunc("/api/login", api.Login);
http.HandleFunc("/api/registration", api.Registration);

/* get your list db */
http.HandleFunc("/api/db/list", api.DataBaseList);

/* server start function */
log.Fatal(http.ListenAndServe(":3000", nil));

}

how not to process a method inside a function

Solution

Maybe this can help you:

type MyHandler struct{}

func (self MyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {

}

http.ListenAndServe(":3000", &MyHandler{})

Answered By – Comin2021

Answer Checked By – Dawn Plyler (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.