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

2024-03-31

我看到一个马特·赖尔撰写的文章 https://medium.com/statuscode/how-i-write-go-http-services-after-seven-years-37c208122831关于如何使用服务器类型和包装器类型的 http 处理程序func(http.ResponseWriter, *http.Request)

我认为这是构建 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

我在解决方案中看到这个帖子 https://stackoverflow.com/questions/26204485/gorilla-mux-custom-middleware我应该使用http.Handle并传入路由器。

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

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

研究中 https://hackernoon.com/simple-http-middleware-with-go-79a4ad62889b这项技术further https://hackernoon.com/simple-http-middleware-with-go-79a4ad62889b,我发现其他读物表明我需要middleware or handler类型定义。

我不完全理解这些示例中发生的情况,因为它们定义的类型似乎没有被使用。

这个资源 https://gist.github.com/ehernandez-xk/f6a941582a3196266a15ad4665f43a60显示了如何编写处理程序,但没有显示如何设置路由。

我确实发现 Gorilla Mux 有内置包装器 https://github.com/gorilla/mux#middleware对于这些东西,但我很难理解 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 https://golang.org/pkg/net/http/#Handler接口,因此这些类型的实例可以用作http.Handle https://golang.org/pkg/net/http/#Handle函数或等效函数http.ServeMux.Handle https://golang.org/pkg/net/http/#ServeMux.Handle method.

一个例子可能会让这一点更清楚:

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 处理函数http.Handler使用http.HandlerFunc https://golang.org/pkg/net/http/#HandlerFunc类型。请注意,签名与签名者的签名相同http.Handler's ServeHTTP method.

例如:

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 处理程序函数而不是实现以下功能的 http 处理程序类型ServeHTTP方法很常见,标准库提供了替代方法http.HandleFunc https://golang.org/pkg/net/http/#HandleFunc and http.ServeMux.HandleFunc https://golang.org/pkg/net/http/#ServeMux.HandleFunc. All HandleFunc所做的就是我们在上面的示例中所做的,它将传入的函数转换为http.HandlerFunc并打电话http.Handle与结果。


http中间件

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

举个例子看看http.StripPrefix https://golang.org/pkg/net/http/#StripPrefix.


现在让我们澄清一些明显的混乱。

#1

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

方法的名称和之前使用的方式,直接传递给HandleFunc,建议您希望这是一个普通的 http 处理程序函数,但签名是中间件的签名,这就是您收到错误的原因:

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

现在,我只会返回 404 调用localhost:8091/sayhello.

问题出在这两行

http.Handle("/sayhello", s.HandleSayHello(s.Router))

and

http.ListenAndServe(":"+config.ServerPort, s.Router)

The http.Handlefunc 将传入的处理程序注册到默认 ServeMux 实例 https://golang.org/pkg/net/http/#DefaultServeMux,它不会将其注册到 gorilla 路由器实例中s.Router正如你似乎假设的那样,然后你就通过了s.Router to the ListenAndServe函数使用它来服务每个请求localhost:8091,并且自从s.Router没有注册处理程序,您会得到404.


#3

但是现在当我设置时如何防止实际函数执行 我的路线?这"before"在我的打印声明中出现之前 服务器启动。

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 method.

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

目的是什么r.Use当它不注册 url 路由时? 怎么handler正在使用?

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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

了解 Go 中的 http handlerfunc 包装器技术 的相关文章

  • Django HTTPS 和 HTTP 会话

    我使用 Django 1 1 1 和 ssl 重定向中间件 通过 HTTPS 创建的会话数据 身份验证等 在站点的 HTTP 部分中不可用 无需将整个站点设置为 HTTPS 即可使其可用的最佳方法是什么 这是设计使然 您无法轻易更改 当通过
  • go中有memset的类似物吗?

    在 C 中 我可以使用某些值初始化数组memset https msdn microsoft com en us library aa246471 28v vs 60 29 aspx const int MAX 1000000 int is
  • 如何绕过 ASP.NET Web API 中发现多个操作的异常

    当试图找到以下问题的解决方案时 默认操作的 MVC Web Api 路由不起作用 https stackoverflow com questions 11724749 mvc web api route with default actio
  • WCF WebHttp 混合身份验证(基本和匿名)

    所有这些都与 WebHttp 绑定有关 托管在自定义服务主机中 IIS 目前不是一个选项 我已经实现了自定义 UserNamePasswordValidator 和自定义 IAuthorizationPolicy 当我将端点的绑定配置为使用
  • 用 C++ 解析 HTTP 标头

    我正在使用curl 与服务器通信 当我发出数据请求时 我收到 HTTP 标头 后跟由边界分隔的 jpeg 数据 如下所示 我需要解析出 边界字符串 内容长度 我已将传入数据复制到 char 数组 如下所示 static size t OnR
  • 如何将 int[] 转换为 uint8[]

    所以 我需要你的帮助 我找不到关于该主题的任何内容 Golang 是一门刚刚诞生的语言 所以对于像我这样的新手来说很难快速找到答案 预先声明的 Goint类型大小是特定于实现的 32 位或 64 位 数字类型 http golang org
  • symfony api 平台深度

    到目前为止 我们一直在 Symfony Doctrine 和 Serializer 深度方面苦苦挣扎 我希望能够使用 Symfony 提供一级深度的 JSON REST API 从而允许我直接从视图管理我的 外键 和关系逻辑 GET peo
  • 端点按资源 swagger 注释分组?

    我正在使用 Spring 进行 REST API 开发 我有一些 API 其中有很多端点 当我打开 swagger ui 时 它看起来很拥挤 我刚刚读过this https swagger io docs specification gro
  • 如何使信号量超时

    Go 中的信号量是通过通道来实现的 一个例子是这样的 https sites google com site gopatterns concurrency semaphores https sites google com site gop
  • 注册期间现有电子邮件的 422 或 409 状态代码

    我正在构建 RESTful API 遇到了一种情况 在用户注册期间 如果电子邮件已存在 则在422 and 409哪个http响应代码有意义 我浏览过类似的one https stackoverflow com questions 9269
  • REST URI 和对象上的操作,可以进行评论、标记、评级等

    我正在为我的公司研究一种 Web API 看起来我们可能会实现一个 RESTful API 我现在已经阅读了几本关于此的书籍 O Reilly 的 RESTful Web 服务 似乎最有用 并为可以评论 标记和评级的对象提出了以下一组 UR
  • Chrome/Firefox 在后台发送两个 POST,间隔恰好 5 秒,仅调用一次来获取 Nodejs 8.0.0 服务器

    注意 这不是飞行前选项 也不是网站图标或其他类似内容 实际上是 2 个帖子 下面有一个屏幕截图可以更清楚地显示这一点 我的规格 版本 macOS 塞拉利昂版本 10 12 3 Chrome 版本 61 0 3128 0 官方版本 开发版 6
  • os.Mkdir 和 os.MkdirAll 权限

    我正在尝试在程序开始时创建一个日志文件 我需要检查是否 log如果不创建目录 则目录存在 然后继续创建日志文件 好吧 我尝试使用os Mkdir 也os MkdirAll 但无论我在第二个参数中输入什么值 我都会得到一个没有权限的锁定文件夹
  • 为 NFL api 生成访问令牌

    NFL 有一个 API 服务 link https api nfl com docs getting started index html https api nfl com docs getting started index html
  • put方法中的Angularjs文件上传不起作用

    我有一个简单的待办事项应用程序 我试图在其中上传照片和单个待办事项 现在我已经创建了这个工厂函数来负责待办事项的创建 todosFactory insertTodo function todo return http post baseUr
  • 在 Gorilla Mux 中嵌套子路由器

    我一直在使用gorilla mux https github com gorilla mux满足我的路由需求 但我注意到一个问题 当我嵌套多个子路由器时它不起作用 这是示例 func main r mux NewRouter StrictS
  • 在 Go 中,如何将结构体转换为字节数组?

    我有一个我定义的结构实例 我想将其转换为字节数组 我尝试了 byte my struct 但这不起作用 另外 我还被指出二进制包 http golang org pkg encoding binary 但我不确定我应该使用哪个函数以及应该如
  • git 是否有任何静态接口?

    我一直在寻找一个宁静的 git api 但似乎没有找到 我得到的最接近的是 Github 的 api 来访问一些存储库信息 还有其他的实施吗 Orion Git API http wiki eclipse org Orion Server
  • select 语句是否保证通道选择的顺序?

    继从这个答案 https stackoverflow com a 25795236 274460 如果一个 goroutine 在两个通道上进行选择 是否保证通道的选择顺序与其发送的顺序相同 我对发送者是单线程的情况特别感兴趣 例如 是否保
  • 我可以在 PHP 会话变量中安全地存储用户名和密码吗?

    我想在 REST api 之上制作一个轻量级的 web 应用程序 用户只需进行一次身份验证 从那时起 所有针对 web api 的请求都希望通过以某种方式保持用户名和密码有效来完成 我已经做了一个工作原型我在哪里将用户名和密码存储在会话变量

随机推荐