Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP handler function

Tags:

go

httphandler

I saw some http handler function declarations are varied. Two of them I found are the standard function and the one returning anonymous function inside the handler. For example:

Using standard way:

func helloworld(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello World")
}

This the most straight way to declare a handler for an http api.

Another way is using anonym/closure function inside the handler function:

func helloworld2() http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
        fmt.Fprintln(w, "Hello World")
    })
}

What are the differences and the benefit? When to use one of them? What's the best practice?

like image 490
blue panther Avatar asked Feb 28 '18 09:02

blue panther


People also ask

What is HTTP handler interface?

The HTTP handler is a Java component that consists of properties. The handler delivers an outbound integration message to a URL by using HTTP or HTTPS protocols. The HTTP handler also evaluates the response code received from the external system.

What is a server handler?

Handlers are Internet Information Services (IIS) components that are configured to process requests to specific content, typically to generate a response for the request resource. For example, an ASP.NET Web page is one type of handler.

What are go handlers?

In Go, a handler is an interface that has a method named ServeHTTP with two parameters: an HTTPResponseWriter interface and a pointer to a Request struct. In other words, anything that has a method called ServeHTTP with this method signature is a handler: ServeHTTP(http.ResponseWriter, *http.Request)

What is go HTTP client?

Go is a language designed by Google for use in a modern internet environment. It comes with a highly capable standard library and a built-in HTTP client.


2 Answers

Pattern

func Middleware(next http.Handler) http.Handler{
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    // Do something
    next.ServeHTTP(w, r)
  })
}

often used to construct middleware chain like

http.Handle("/", middlewareOne(middlewareTwo(finalHandler)))
like image 104
Uvelichitel Avatar answered Sep 28 '22 07:09

Uvelichitel


Returning an anonymous function is the only way to work with handlers that require additional arguments, by returning a closure. Example:

func fooHandler(db *someDatabase) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // do something with `db` variable
    }
}

Otherwise, there's typically no practical difference between the approaches. One may choose to use the anonymous function universally for consistency.

like image 23
Flimzy Avatar answered Sep 28 '22 05:09

Flimzy