Last active
May 9, 2024 17:56
-
-
Save dlisboa/f8dba166a0430b2aed4712d75f1e5041 to your computer and use it in GitHub Desktop.
Go Middlewares
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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