Skip to content

Instantly share code, notes, and snippets.

@dlisboa
Last active May 9, 2024 17:56
Show Gist options
  • Save dlisboa/f8dba166a0430b2aed4712d75f1e5041 to your computer and use it in GitHub Desktop.
Save dlisboa/f8dba166a0430b2aed4712d75f1e5041 to your computer and use it in GitHub Desktop.
Go Middlewares
package middleware
import (
"net/http"
"strings"
)
func Method(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
switch strings.ToLower(r.PostFormValue("_method")) {
case "put":
r.Method = http.MethodPut
case "patch":
r.Method = http.MethodPatch
case "delete":
r.Method = http.MethodDelete
default:
}
}
next.ServeHTTP(w, r)
})
}
mux := http.NewServeMux()
mux.Handle("POST /", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(r.Method))
})
mux.Handle("PUT /", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(r.Method))
})
var handler http.Handler = mux
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment