如何处理来自 go 的请求方法。我不使用图书馆

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

在那之前我使用 node js 并且很容易理解如何处理方法

节点 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);

}

但是我不知道该怎么做

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
);

如何在 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));

}

如何不在函数内部处理方法

这是翻译成 Go 的问题中的 node.js 代码。 Go 代码与 node.js 代码非常相似。

func myHandler(response http.ResponseWriter, request *http.Request) {
    switch request.Method {
    case "OPTIONS":
        OptionsResponse(response, request)
    case "GET":
        GetSwitch(response, request)
    case "POST":
        PostSwitch(response, request)
    case "PUT":
        PutSwitch(response, request)
    case "DELETE":
        DeleteSwitch(response, request)
    default:
        http.Error(response, "Sorry, this method not supported", 501)
    }
}

我认为您需要为您的代码编写响应和请求 像这样。因为是语言的默认包

func myHandler(w http.ResponseWriter, r *http.Request) {
switch request.Method {
case "OPTIONS":
    OptionsResponse(response, request)
case "GET":
    GetSwitch(response, request)
case "POST":
    PostSwitch(response, request)
case "PUT":
    PutSwitch(response, request)
case "DELETE":
    DeleteSwitch(response, request)
default:
    http.Error(response, "Sorry, this method not supported", 501)
}

}

也许这可以帮到你:

type MyHandler struct{}

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

}

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