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


77

我试图找出最好的方式来处理对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库做的最好的吗?我宁愿做一些http.HandleGet("/", handler)快递或西纳特拉之类的事情。有没有编写简单REST服务的良好框架?web.go看起来很吸引人,但停滞不前。

感谢您的意见。


2
如果您只是在寻找路由抽象,则可能对gorillatoolkit.org/pkg/mux感兴趣。
dskinner

1
+1。mux或gorillatoolkit.org/pkg/pat非常适合抽象此内容。
minikomi

Answers:


96

确保只为根服务:做正确的事。在某些情况下,您可能想调用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:
    // Give an error message.
}

当然,您可能会发现像gorilla这样的第三方软件包对您来说更好。


32

嗯,我实际上要上床睡觉了,因此快速浏览一下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 lib太裸了,那么可以在这里查看大量资源:https : //github.com/golang/go/wiki/Projects#web-libraries(专门链接到Web库)。


并且不要忘记r在您的Server实例
中将
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.