rest - 了解 Go 中的 http handlerfunc 包装器技术

标签 rest http go wrapper gorilla

我看到一个 article written by Mat Ryer关于如何使用作为 func(http.ResponseWriter, *http.Request) 包装器类型的服务器类型和 http 处理程序

我认为这是构建 REST API 的一种更优雅的方式,但是我完全无法让包装器正常运行。我要么在编译时遇到类型不匹配的错误,要么在调用时遇到 404。

这基本上是我目前用于学习目的的内容。

package main

import(
   "log"
   "io/ioutil"
   "encoding/json"
   "os"
   "net/http"
   "github.com/gorilla/mux"
)

type Config struct {
   DebugLevel int `json:"debuglevel"`
   ServerPort string `json:"serverport"`
}

func NewConfig() Config {

   var didJsonLoad bool = true

   jsonFile, err := os.Open("config.json")
   if(err != nil){
      log.Println(err)
      panic(err)
      recover()
      didJsonLoad = false
   }

   defer jsonFile.Close()

   jsonBytes, _ := ioutil.ReadAll(jsonFile)

   config := Config{}

   if(didJsonLoad){
      err = json.Unmarshal(jsonBytes, &config)
      if(err != nil){
         log.Println(err)
         panic(err)
         recover()
      }
   }

   return config
}

type Server struct {
   Router *mux.Router
}

func NewServer(config *Config) *Server {
   server := Server{
      Router : mux.NewRouter(),
   }

   server.Routes()

   return &server
}

func (s *Server) Start(config *Config) {
   log.Println("Server started on port", config.ServerPort)
   http.ListenAndServe(":"+config.ServerPort, s.Router)
}

func (s *Server) Routes(){
   http.Handle("/sayhello", s.HandleSayHello(s.Router))
}

func (s *Server) HandleSayHello(h http.Handler) http.Handler {
   log.Println("before")
   return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
      w.Write([]byte("Hello."))
      h.ServeHTTP(w, r)
   })
}

func main() {
   config := NewConfig()
   server := NewServer(&config)
   server.Start(&config)
}

由于现在是这样,我只会返回 404 调用 localhost:8091/sayhello . (是的,这是我在配置文件中设置的端口。)

之前,因为我使用的是 Gorilla Mux,所以我设置了这样的处理程序:
func (s *Server) Routes(){
    s.Router.HandleFunc("/sayhello", s.HandleSayHello)
}

这给了我这个错误,我完全被难住了。cannot use s.HandleSayHello (type func(http.Handler) http.Handler) as type func(http.ResponseWriter, *http.Request) in argument to s.Router.HandleFunc
我在 this SO post 的解决方案中看到了我应该使用 http.Handle并传入路由器。
func (s *Server) Routes(){
   http.Handle("/sayhello", s.HandleSayHello(s.Router))
}

但是现在如何在设置路由时阻止实际功能的执行? "before"在我的打印语句中出现在服务器启动之前。我现在不认为这是一个问题,但是一旦我开始为数据库查询编写更复杂的中间件,我可能会使用它。

Researching此技术further ,我发现其他阅读建议我需要一个 middlewarehandler类型定义。

我不完全理解这些示例中发生了什么,因为它们定义的类型似乎没有得到使用。

This resource显示处理程序是如何编写的,但没有显示路由是如何设置的。

我确实发现 Gorilla Mux 有 built in wrappers对于这些东西,但我很难理解 API。

他们展示的例子是这样的:
func loggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Do stuff here
        log.Println(r.RequestURI)
        // Call the next handler, which can be another middleware in the chain, or the final handler.
        next.ServeHTTP(w, r)
    })
}

路由是这样定义的:
r := mux.NewRouter()
r.HandleFunc("/", handler)
r.Use(loggingMiddleware)
r.Use的目的是什么?当它没有注册 url 路由时?
怎么样handler正在使用?

当我的代码这样写时,我没有得到编译错误,但我不明白我的函数是如何写回“Hello”的。我想我可以使用 w.Write在错误的地方。

最佳答案

我认为您可能将“中间件”与真正的处理程序混为一谈。

http 处理程序

实现 ServeHTTP(w http.ResponseWriter, r *http.Request) 的类型方法满足 http.Handler 接口(interface),因此这些类型的实例可以用作 http.Handle 的第二个参数。函数或等效函数 http.ServeMux.Handle 方法。

一个例子可能会更清楚地说明这一点:

type myHandler struct {
    // ...
}

func (h myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte(`hello world`))
}

func main() {
    http.Handle("/", myHandler{})
    http.ListenAndServe(":8080", nil)
}

http 处理函数

带有签名的函数 func(w http.ResponseWriter, r *http.Request)是可以转换为 http.Handler 的 http 处理程序函数使用 http.HandlerFunc 类型。注意签名与http.Handler的签名相同。的 ServeHTTP方法。

例如:
func myHandlerFunc(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte(`hello world`))
}

func main() {
    http.Handle("/", http.HandlerFunc(myHandlerFunc))
    http.ListenAndServe(":8080", nil)
}

表达式 http.HandlerFunc(myHandlerFunc)转换 myHandlerFunc函数类型 http.HandlerFunc它实现了 ServeHTTP方法,因此该表达式的结果值是有效的 http.Handler因此它可以传递给 http.Handle("/", ...)函数调用作为第二个参数。

使用普通的 http 处理程序函数而不是实现 ServeHTTP 的 http 处理程序类型方法很常见,标准库提供了替代方法 http.HandleFunc http.ServeMux.HandleFunc .全部 HandleFunc do就是我们在上面的例子中所做的,它将传入的函数转换为http.HandlerFunc并调用 http.Handle结果。

http中间件

具有与此类似的签名的函数 func(h http.Handler) http.Handler被视为中间件。请记住,中间件的签名不受限制,您可以让中间件接受比单个处理程序更多的参数并返回更多值,但通常一个函数至少需要一个处理程序并至少重新运行一个新的处理程序可以被认为是中间件。

http.StripPrefix 为例。 .

现在让我们清除一些明显的混淆。

#1
func (s *Server) HandleSayHello(h http.Handler) http.Handler {

方法名和你之前使用的方式,直接传给HandleFunc , 建议您希望这是一个普通的 http 处理程序 func,但签名是中间件的签名,这就是您得到错误的原因:
cannot use s.HandleSayHello (type func(http.Handler) http.Handler) as type func(http.ResponseWriter, *http.Request) in argument to s.Router.HandleFunc

因此,将您的代码更新为类似于下面的代码将消除该编译错误,并且还将正确呈现 "Hello."访问时的文字 /sayhello .
func (s *Server) HandleSayHello(w http.ResponseWriter, r *http.Request) {
      w.Write([]byte("Hello."))
}

func (s *Server) Routes(){
    s.Router.HandleFunc("/sayhello", s.HandleSayHello)
}

#2

As this is right now, I'll only get back a 404 invoking localhost:8091/sayhello.



问题出在这两行
http.Handle("/sayhello", s.HandleSayHello(s.Router))


http.ListenAndServe(":"+config.ServerPort, s.Router)
http.Handle func 使用 default ServeMux instance 注册传入的处理程序,它不会在s.Router中的gorilla路由器实例中注册它正如您似乎假设的那样,然后您正在通过 s.RouterListenAndServe func 使用它来服务来自 localhost:8091 的每个请求,以及自 s.Router没有注册的处理程序,你会得到 404 .

#3

But now how do I prevent the actual function from executing when I set my routes? The "before" in my print statement is showing up before the server starts.


func (s *Server) Routes(){
   http.Handle("/sayhello", s.HandleSayHello(s.Router))
}

func (s *Server) HandleSayHello(h http.Handler) http.Handler {
   log.Println("before")
   return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
      w.Write([]byte("Hello."))
      h.ServeHTTP(w, r)
   })
}

取决于您所说的“实际功能”是什么意思。在 Go 中,您可以通过在名称末尾添加括号来执行函数。所以当你设置路由时,这里执行的是 http.Handle函数和 HandleSayHello方法。
HandleSayHello方法在其主体中有两个语句,函数调用表达式语句 log.Println("before")和返回语句 return http.HandlerFunc(...并且每次调用 HandleSayHello 时都会执行这两个操作.然而,当您调用 HandleSayHello 时,返回函数内的语句,即处理程序,将不会被执行。 ,而是在调用返回的处理程序时执行它们。

你不要"before"打印时 HandleSayHello被调用但您希望在调用返回的处理程序时打印它?您需要做的就是将日志行向下移动到返回的处理程序:
func (s *Server) HandleSayHello(h http.Handler) http.Handler {
   return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
      log.Println("before")
      w.Write([]byte("Hello."))
      h.ServeHTTP(w, r)
   })
}

这段代码现在当然没有什么意义,即使作为教育目的的例子,它也会混淆而不是澄清处理程序和中间件的概念。

相反,也许可以考虑这样的事情:
// the handler func
func (s *Server) HandleSayHello(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello."))
}

// the middleware
func (s *Server) PrintBefore(h http.Handler) http.Handler {
       return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
               log.Println("before") // execute before the actual handler
               h.ServeHTTP(w, r)     // execute the actual handler
       })
}

func (s *Server) Routes(){
        // PrintBefore takes an http.Handler but HandleSayHello is an http handler func so
        // we first need to convert it to an http.Hanlder using the http.HandlerFunc type.
        s.Router.HandleFunc("/sayhello", s.PrintBefore(http.HandlerFunc(s.HandleSayHello)))
}

#4
r := mux.NewRouter()
r.HandleFunc("/", handler)
r.Use(loggingMiddleware)

What is the purpose of r.Use when it's not registering the url route? How is handler being used?


Use在路由器级别注册中间件,这意味着在该路由器上注册的所有处理程序都将在执行中间件之前先执行中间件。

例如上面的代码等价于:
r := mux.NewRouter()
r.HandleFunc("/", loggingMiddleware(handler))

当然Use不是为了不必要和困惑,如果您有许多端点都具有不同的处理程序,并且所有端点都需要一堆中间件来应用于它们,这将很有用。

然后像这样编码:
r.Handle("/foo", mw1(mw2(mw3(foohandler))))
r.Handle("/bar", mw1(mw2(mw3(barhandler))))
r.Handle("/baz", mw1(mw2(mw3(bazhandler))))
// ... hundreds more

可以从根本上简化:
r.Handle("/foo", foohandler)
r.Handle("/bar", barhandler)
r.Handle("/baz", bazhandler)
// ... hundreds more
r.Use(mw1, mw2, m3)

关于rest - 了解 Go 中的 http handlerfunc 包装器技术,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53678633/

相关文章:

java - Spring Boot @RestController没有响应

php - localhost 目前无法处理此请求。 Laravel 的 HTTP 错误 500

mongodb - Golang MGO Group By multiple params 并按日期时间抓取最后一个

go - 如何在 Controller 访问的中间件中使用保存在上下文中的 "type struct"

rest - 当 REST 资源链接到现有资源并对其进行扩展时,如何处理?

java - 返回 UI 时,数字类型列的最大值会增加

java - OkHttpClient - 忽略系统属性中的代理

http - 用于字节 blob 的 HTTP "content-type"是什么?

javascript - 设置 'Content-disposition' 而不设置 'Content-Length' 是否可以接受?

go - Go中嵌套结构的问题