小编典典

如何在 Go 中处理对 / 的不同方法的 http 请求?

go

我试图找出处理对Go 的请求的最佳方式,/并且只/在 Go 中处理,并以不同的方式处理不同的方法。这是我想出的最好的:

package main

import (
    "fmt"
    "html"
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        if r.URL.Path != "/" {
            http.NotFound(w, r)
            return
        }

        if r.Method == "GET" {
            fmt.Fprintf(w, "GET, %q", html.EscapeString(r.URL.Path))
        } else if r.Method == "POST" {
            fmt.Fprintf(w, "POST, %q", html.EscapeString(r.URL.Path))
        } else {
            http.Error(w, "Invalid request method.", 405)
        }
    })

    log.Fatal(http.ListenAndServe(":8080", nil))
}

这是惯用的 Go 语言吗?这是我能用标准 http lib 做的最好的事情吗?我更愿意做一些像http.HandleGet("/", handler)express 或 Sinatra那样的事情。是否有编写简单 REST 服务的好框架?web.go看起来很有吸引力,但似乎停滞不前。

感谢您的建议。


阅读 241

收藏
2021-12-12

共1个答案

小编典典

确保您只为根服务:您在做正确的事情。在某些情况下,您可能希望调用 http.FileServer 对象的 ServeHttp 方法而不是调用 NotFound;这取决于您是否还有其他要提供的文件。

以不同的方式处理不同的方法:我的许多 HTTP 处理程序只包含一个像这样的 switch 语句:

switch r.Method {
case http.MethodGet:
    // Serve the resource.
case http.MethodPost:
    // Create a new record.
case http.MethodPut:
    // Update an existing record.
case http.MethodDelete:
    // Remove the record.
default:
    http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}

当然,您可能会发现像 gorilla 这样的第三方软件包更适合您。

2021-12-12