【问题标题】:How can I handle http requests of different methods to / in Go?如何在 Go 中处理不同方法的 http 请求?
【发布时间】:2013-02-20 20:41:56
【问题描述】:

我正在尝试找出在 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))
}

这是惯用的围棋吗?这是我能用标准http lib做的最好的吗?我更愿意在 express 或 Sinatra 中做类似http.HandleGet("/", handler) 的事情。是否有编写简单 REST 服务的良好框架? web.go 看起来很吸引人,但似乎停滞不前。

感谢您的建议。

【问题讨论】:

标签: go


【解决方案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 这样的第三方软件包更适合您。

【讨论】:

  • 在默认分支“给出错误消息”中,您应该返回 HTTP 状态代码 405,即w.WriteHeader(http.StatusMethodNotAllowed)
【解决方案2】:

嗯,我实际上是去睡觉了,因此对http://www.gorillatoolkit.org/pkg/mux 的快速评论非常好,并且可以满足您的需求,只需查看文档即可。例如

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/", HomeHandler)
    r.HandleFunc("/products", ProductsHandler)
    r.HandleFunc("/articles", ArticlesHandler)
    http.Handle("/", r)
}

r.HandleFunc("/products", ProductsHandler).
    Host("www.domain.com").
    Methods("GET").
    Schemes("http")

以及执行上述操作的许多其他可能性和方式。

但我觉得有必要解决问题的另一部分,“这是我能做的最好的吗”。如果 std 库有点过于简单,可以在这里查看一个很好的资源:@​​987654322@(专门链接到网络库)。

【讨论】:

  • 别忘了将新路由器r注册为Server实例中的处理程序
猜你喜欢
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 2021-11-06
  • 2013-01-03
  • 2015-09-19
  • 1970-01-01
  • 1970-01-01
  • 2015-10-18
相关资源
最近更新 更多