Here's the equivalent code in Go using the standard net/http package and a popular router like gorilla/mux:
go
package main
import (
"encoding/json"
"net/http"
"github.com/gorilla/mux"
)
func main() {
r := mux.NewRouter()
// Middleware to parse URL-encoded form data
r.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Parse form data (similar to bodyParser.urlencoded({ extended: false }))
if err := r.ParseForm(); err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
next.ServeHTTP(w, r)
})
})
// Middleware to parse JSON bodies
r.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Only parse JSON for appropriate content types
if r.Header.Get("Content-Type") == "application/json" {
var data interface{}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
// You might want to store the parsed data in the context
// ctx := context.WithValue(r.Context(), "parsedJSON", data)
// r = r.WithContext(ctx)
}
next.ServeHTTP(w, r)
})
})
// Your routes would go here
// r.HandleFunc("/", handlerFunction)
http.ListenAndServe(":8080", r)
}
Key differences:
In Go, middleware is implemented as functions that wrap http.Handler types
r.ParseForm() handles URL-encoded form data (similar to bodyParser.urlencoded)
json.NewDecoder().Decode() handles JSON parsing (similar to bodyParser.json())
The Gorilla mux router is used here as it's a popular choice, but you could also use the standard library alone
Pure standard library version:
If you prefer not to use third-party packages, here's a version using only the standard library:
go
package main
import (
"encoding/json"
"net/http"
)
func urlEncodedMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
next.ServeHTTP(w, r)
})
}
func jsonMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-Type") == "application/json" {
var data interface{}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
}
next.ServeHTTP(w, r)
})
}
func main() {
mux := http.NewServeMux()
// Your handler would be registered here
// mux.HandleFunc("/", handler)
// Wrap the mux with middleware
handler := urlEncodedMiddleware(jsonMiddleware(mux))
http.ListenAndServe(":8080", handler)
}