90

I'm trying to figure out the best way to handle requests to / and only / in Go and handle different methods in different ways. Here's the best I've come up with:

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

Is this idiomatic Go? Is this the best I can do with the standard http lib? I'd much rather do something like http.HandleGet("/", handler) as in express or Sinatra. Is there a good framework for writing simple REST services? web.go looks attractive but appears stagnant.

Thank you for your advice.

4

2 回答 2

115

确保您只为根服务:您正在做正确的事情。在某些情况下,您可能希望调用 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 这样的第三方软件包更适合您。

于 2013-03-06T16:57:55.857 回答
40

嗯,我实际上是去睡觉了,因此对查看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 库有点过于简单,可以在这里查看一个很好的资源:https ://github.com/golang/go/wiki/Projects#web-libraries (专门链接到 Web 库)。

于 2013-03-06T07:51:49.650 回答