使用标准库实现的Golang中间件

huangapple go评论132阅读模式
英文:

Golang middleware with just the standard library

问题

我的第一个stackoverflow问题,请对我对stackoverflow和所提问题的幼稚态度宽容一些,我是golang的初学者。

我想知道这两个调用之间的区别,以及对HandleHandlerHandleFuncHandlerFunc的简单理解。

http.Handle("/profile", Logger(profilefunc))
http.HandleFunc("/", HomeFunc)
func main() {
   fmt.Println("Starting the server.")
  
   profilefunc := http.HandlerFunc(ProfileFunc)
    
   http.Handle("/profile", Logger(profilefunc))
   http.HandleFunc("/", HomeFunc)
      
   http.ListenAndServe("0.0.0.0:8081", nil)
}

func Logger(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
        log.Println("Before serving request")
        h.ServeHTTP(w, r)
        log.Println("After serving request")
    })
}

func ProfileFunc(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "You are on the profile page.")
}

func HomeFunc(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello Imran Pochi")
}
英文:

My first stackoverflow question, so please go easy on my naivety about stackoverflow and the question asked, beginner in golang.

I would like to know the difference between the two calls and also simple understanding of the Handle, Handler, HandleFunc, HandlerFunc.

> http.Handle("/profile", Logger(profilefunc))
> http.HandleFunc("/", HomeFunc)

func main() {            
   fmt.Println("Starting the server.")
      
   profilefunc := http.HandlerFunc(ProfileFunc)
    
   http.Handle("/profile", Logger(profilefunc))
   http.HandleFunc("/", HomeFunc)
      
   http.ListenAndServe("0.0.0.0:8081", nil)
}
        
func Logger(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
        log.Println("Before serving request")
    	h.ServeHTTP(w, r)
    	log.Println("After serving request")
    })
}
    
func ProfileFunc(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "You are on the profile page.")
}
    
func HomeFunc(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello Imran Pochi")
}

答案1

得分: 2

根据我从Go文档示例中看到的内容:

  • Handler 是一个用于响应HTTP请求的类型。要将一个类型变为Handler,只需实现一个 ServeHTTP() 方法。ServeHTTP() 方法执行实际的请求处理。

  • Handle() 接受路由和一个Handler,该Handler是一个具有名为 ServeHTTP() 的实例方法的类型。注意它只接受类型,不需要显式指向处理请求的实际方法/函数。

  • HandlerFunc 是一个内部实现了 ServeHTTP() 方法的类型。HandlerFunc 用于将任何具有正确签名的Go函数转换为 HandlerFunc。然后,新创建的 HandlerFunc 与它处理的路由一起传递给 Handle() 方法。
    请注意,HandlerFunc 允许通过编写函数来实现请求处理程序,而无需专门的处理程序类型。

  • HandleFunc() 接受一个路由和任何具有正确签名的函数。HandleFunc 是首先进行类型转换,然后将函数传递给 Handle() 方法的简写形式。

请求处理函数的签名如下:

  func handlerName(wr http.ResponseWriter, req *http.Request)
英文:

According to what I've seen from the Go documentation examples:

  • A Handler is a type created to respond to an HTTP request. To make a type a Handler all one has to do is implement a ServeHTTP() method. The ServeHTTP() method does the actual request processing.

  • Handle() takes the route and a Handler, the type that has an instance method named ServeHttp(). Note that it just takes the type, there's no need for one to point at the actual method/function that handles the request explicitly.

  • HandlerFunc is a type that internally implements a ServeHTTP() method. HandlerFunc is used to cast any Go function, with the right signature, to a HandlerFunc. The newly minted HandlerFunc is then passed to the Handle() method together with the route it processes.
    Note that the HandlerFunc lets one implement request handlers by just writing functions without the need for a dedicated handler type.

  • HandleFunc() takes a route and any function that has the right signature. HandleFunc is shorthand for first of all doing the type casting and then passing the function to the Handle() method.

The signature for a request handling function is:

  func handlerName(wr http.ResponseWriter, req *http.Request)

答案2

得分: 2

  • Handler 是一个接口,可以响应 HTTP 请求,并具有 ServeHTTP(ResponseWriter, *Request) 方法。
  • http.Handle 注册一个 Handler 来处理与给定 pattern 匹配的 HTTP 请求。
  • http.HandleFunc 注册一个处理函数来处理与给定 pattern 匹配的 HTTP 请求。处理函数的形式应为 func(ResponseWriter, *Request)
  • HandlerFunc 是一个显式的函数类型,形式为 func(ResponseWriter, *Request)HandlerFunc 有一个名为 ServeHTTP 的方法,该方法调用自身。这允许你将一个函数转换为 HandlerFunc 并将其用作 Handler

Logger 是一个中间件的示例,它是一个接受 http.Handler 并返回另一个包装了原始处理程序的 http.Handler 的函数。当调用此处理程序时,它可能(或可能不会)在执行某些操作之前和/或之后调用嵌套的 http.Handler。因此,第一行代码表示注册使用 Logger 中间件包装的 profileFunc Handler,并将其与模式 "/profile" 关联。第二行代码表示注册 HomeFunc 函数,并将其与模式 "/" 关联。

英文:

> I would like ... simple understanding of the Handle, Handler, HandleFunc, HandlerFunc.

  • Handler is an interface that can respond to an HTTP request and has a ServeHTTP(ResponseWriter, *Request) method.
  • http.Handle registers a Handler to handle HTTP requests matching a given pattern.
  • http.HandleFunc registers a handler function to handle HTTP requests matching a given pattern. The handler function should be of the form func(ResponseWriter, *Request).
  • HandlerFunc is an explicit function type of the form func(ResponseWriter, *Request). HandlerFunc has a method ServeHTTP that calls itself . This allows you to cast a function to a HandlerFunc and use it as a Handler.

> I would to know the difference between the two calls

http.Handle("/profile", Logger(profilefunc))
http.HandleFunc("/", HomeFunc)

Logger is an example of a middleware, which is a function that takes an http.Handler and it returns another http.Handler that wraps the original handler. When called this handler may (or may not) call the nested http.Handler before and/or after performing some operation. So the first line is saying register the profileFunc Handler wrapped in the Logger middleware with the pattern "/profile". The second line is saying register the HomeFunc function with the "/" pattern.

huangapple
  • 本文由 发表于 2017年5月22日 18:42:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/44110834.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定