回答

收藏

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

技术问答 技术问答 300 人阅读 | 0 人回复 | 2023-09-12

我试图找出正确的处理方法Go 请求的最佳方式,/和只/在 Go 中处理,以不同的方式处理不同的方法。这是我最好的想法:
/ j7 L5 ~1 K# @4 N
    package mainimport (    "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 == &quotOST"                  fmt.Fprintf(w,&quotOST,%q",html.EscapeString(r.URL.Path))      else                http.Error(w,"Invalid request method.",405)         })    log.Fatal(http.ListenAndServe(":8080",nil))}# E& D' r. {/ _$ w, C3 j; n4 ^( _: o8 a
这是惯用 Go 语言http lib 做最好的事吗?我更喜欢做一些事情,就像http.HandleGet("/",handler)express 或 Sinatra那样的事情。有没有简单的写作 REST 良好的服务框架?web.go看上去很有吸引力,但似乎停滞不前。
2 `" T$ d; n' _) W" [; ?7 P# ]3 f感谢您的建议。4 a0 c4 s( H' B
                                                                " D# L2 ?; f: |- w  I: p- j" ^- D# o
    解决方案:                                                                & B- v: I* e9 N2 ?) X
                                                                确保你只为根服务:你在做正确的事情。在某些情况下,您可能希望调用 http.FileServer 对象的 ServeHttp 方法而不是调用 NotFound;这取决于你是否还有其他文件要提供。
8 A( ~% t0 x9 g0 P/ S以不同的方式处理不同的方法:我的许多 HTTP 处理程序只包含这样的 switch 语句:
* ~! H5 L& }) g7 k. |* @5 C
    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)}$ P9 n6 F" L* k6 E
当然,你可能会发现 gorilla 这样的第三方软件包更适合你。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则