The net/http server automatically starts a new goroutine for each client connection and executes request handlers in those goroutines. The application does not need to do anything special to serve requests concurrently.

Use a mutex to protect these values if they are not thread-safe. The mux (assuming you are using gorilla/mux) and the controller (as currently written) are both thread-safe.

Middlewares:

func main() {
    r := mux.NewRouter()
    r.Use(middleware1)
    r.Use(middleware2)
    r.Use(middleware3)
    r.HandleFunc("/", index)
    http.ListenAndServe(":8080", r)
}
func middleware1(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Perform some task, such as logging
        log.Println("Middleware 1")
        // Call the next handler
        next.ServeHTTP(w, r)
    })
}
 
func middleware2(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Perform some task, such as validating a request
        if r.Method != "GET" {
            http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
            return
        }
        // Call the next handler
        next.ServeHTTP(w, r)
    })
}
 
func middleware3(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Perform some task, such as adding a custom header to the response
        w.Header().Add("X-Custom-Header", "example")
        // Call the next handler
        next.ServeHTTP(w, r)
    })
}

Middleware to add CORS:

package main
 
import (
    "net/http"
 
    "github.com/gorilla/mux"
)
 
func corsMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Access-Control-Allow-Origin", "*")
        w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
        w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
        next.ServeHTTP(w, r)
    })
}
 
func main() {
    r := mux.NewRouter()
    r.Use(corsMiddleware)
    r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello, World!"))
    })
    http.ListenAndServe(":8000", r)
}

🌱 Back to Garden