Richard Rublev
Richard Rublev

Reputation: 8164

How does creating handlers works?

I am looking at this example

var name string

type helloWorldResponse struct {
    Message string `json:"message"`
}

type helloWorldRequest struct {
    Name string `json:"name"`
}

func main() {
    port := 8080

    handler := newValidationHandler(newHelloWorldHandler())
    http.Handle("/helloworld", handler)
    log.Printf("Server starting on port %v\n", port)
    log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", port), nil))
}

type validationHandler struct {
    next http.Handler
}

func newValidationHandler(next http.Handler) http.Handler {
    return validationHandler{next: next}
}

func (h validationHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
    var request helloWorldRequest
    decoder := json.NewDecoder(r.Body)

    err := decoder.Decode(&request)
    if err != nil {
        http.Error(rw, "Bad request", http.StatusBadRequest)
        return
    }

    name = request.Name
    h.next.ServeHTTP(rw, r)
}

type helloWorldHandler struct{}

func newHelloWorldHandler() http.Handler {
    return helloWorldHandler{}
}

func (h helloWorldHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
    response := helloWorldResponse{Message: "Hello " + name}

    encoder := json.NewEncoder(rw)
    encoder.Encode(response)
}

The author of the code explained that we are going to be chaining handlers together, the first handler, which is our validation handler, needs to have a reference to the next in the chain as it has the responsibility for calling ServeHTTP or returning a response. I am newbe to Go and I do not understand this line

return validationHandler{next: next}

Which data structure next:next represents?

Upvotes: -1

Views: 47

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

type validationHandler struct {
    next http.Handler // 1
}

func newValidationHandler(next /* 2 */ http.Handler) http.Handler { 
    return validationHandler{next: next} 
    //                         1     2
}

next number 1 is a field from validationHandler struct (a few lines above). And the other next is method's parameter (from the signature). All in all, this simply sets a field in a struct. No magic.

Which data structure next:next represents?

Not a data structure. It is struct initialization syntax. See more examples here: https://gobyexample.com/structs

Upvotes: 3

Related Questions