Sobes.tech
Senior

Mis on middleware Go HTTP serverites ja kuidas see rakendatakse?

sobes.tech AI

Vastus AI-lt

Middleware in Go HTTP servers is a function or set of functions that wrap the request handler (http.Handler) to add additional logic, such as logging, authentication, error handling, etc.

It is implemented as a function that takes an http.Handler and returns an http.Handler. Example:

func loggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log.Printf("Request: %s %s", r.Method, r.URL.Path)
        next.ServeHTTP(w, r) // call the next handler
    })
}

// Usage
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello"))
})

loggedMux := loggingMiddleware(mux)
http.ListenAndServe(":8080", loggedMux)

This way, middleware allows sequential processing of requests, adding necessary functional layers without changing the main handler.