The Express.js code you provided sets up a web server and registers two middleware functions: one for parsing URL-encoded request bodies and another for parsing JSON request bodies.
In Go, the approach is slightly different because net/http (the standard library for HTTP) and common routers don't automatically populate a req.body object like Express does. You typically parse the body inside your handler function, or you create middleware that reads the body and puts the parsed data into the request's context.Context for later retrieval by the handler.
Here's a breakdown of equivalent approaches in Go:
1. Using Standard Library net/http (Most Idiomatic Go)
This is the most common way to handle body parsing in Go. Instead of global middleware, you parse the request body directly within the specific handler that needs it.
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
)
// MyJSONRequestBody represents a typical JSON request body
type MyJSONRequestBody struct {
Name string `json:"name"`
Value int `json:"value"`
}
// MyFormRequestBody represents a typical URL-encoded form request body
type MyFormRequestBody struct {
FirstName string `form:"firstName"`
LastName string `form:"lastName"`
}
// jsonHandler handles requests with JSON bodies
func jsonHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
if r.Header.Get("Content-Type") != "application/json" {
http.Error(w, "Content-Type must be application/json", http.StatusUnsupportedMediaType)
return
}
var data MyJSONRequestBody
// Decode the JSON body directly into the struct
err := json.NewDecoder(r.Body).Decode(&data)
if err != nil {
http.Error(w, "Bad request: "+err.Error(), http.StatusBadRequest)
return
}
fmt.Printf("Received JSON: Name='%s', Value=%d\n", data.Name, data.Value)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"message": "JSON received successfully"})
}
// formHandler handles requests with URL-encoded form bodies
func formHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// ParseForm parses the URL-encoded form data, if any, from the request body.
// It's crucial for accessing form values via r.Form or r.PostForm.
err := r.ParseForm()
if err != nil {
http.Error(w, "Bad request: "+err.Error(), http.StatusBadRequest)
return
}
// Access form values using r.PostForm.Get() or r.Form.Get()
firstName := r.PostForm.Get("firstName")
lastName := r.PostForm.Get("lastName")
fmt.Printf("Received Form: FirstName='%s', LastName='%s'\n", firstName, lastName)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"message": "Form data received successfully"})
}
// defaultHandler for root path or unhandled routes
func defaultHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, Go Web!")
}
func main() {
mux := http.NewServeMux() // http.ServeMux is Go's built-in router
mux.HandleFunc("/", defaultHandler)
mux.HandleFunc("/submit-json", jsonHandler)
mux.HandleFunc("/submit-form", formHandler)
log.Println("Server starting on :8080...")
log.Fatal(http.ListenAndServe(":8080", mux))
}
/*
To test this:
1. Save as `main.go`.
2. Run `go mod init myapp` (if not already in a module)
3. Run `go run main.go`
Test with curl:
JSON POST:
curl -X POST -H "Content-Type: application/json" -d '{"name": "Alice", "value": 123}' http://localhost:8080/submit-json
Form POST:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'firstName=John&lastName=Doe' http://localhost:8080/submit-form
GET:
curl http://localhost:8080/
*/
Explanation:
http.NewServeMux(): This is Go's built-in HTTP request multiplexer (router).
mux.HandleFunc("/path", handlerFunction): Registers a handler for a specific path.
json.NewDecoder(r.Body).Decode(&data): For JSON, you create a new JSON.Decoder from the request's Body (which is an io.Reader) and Decode it directly into a Go struct.
r.ParseForm(): For URL-encoded forms, this function parses the body. After calling it, you can access form fields using r.PostForm.Get("fieldName") or r.Form.Get("fieldName").
http.ListenAndServe(":8080", mux): Starts the HTTP server on port 8080, using mux to handle requests.
2. Using a Third-Party Router like gorilla/mux (More Express-like Middleware)
Many Go web frameworks or routers provide a Use method similar to Express for middleware chaining. gorilla/mux is a very popular choice.
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"github.com/gorilla/mux" // Import gorilla/mux
)
// Define structs for request bodies (same as above)
type MyJSONRequestBody struct {
Name string `json:"name"`
Value int `json:"value"`
}
type MyFormRequestBody struct {
FirstName string `form:"firstName"`
LastName string `form:"lastName"`
}
// Key for storing parsed data in context
type contextKey string
const (
parsedJSONKey contextKey = "parsedJSON"
parsedFormKey contextKey = "parsedForm"
)
// Middleware for JSON body parsing (can be applied to specific routes or globally)
func jsonBodyParserMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost && r.Header.Get("Content-Type") == "application/json" {
var data MyJSONRequestBody
err := json.NewDecoder(r.Body).Decode(&data)
if err != nil {
// Don't just return, wrap the error in context or log it
log.Printf("JSON decoding error: %v", err)
http.Error(w, "Bad JSON request: "+err.Error(), http.StatusBadRequest)
return // Stop processing this request
}
// Store the parsed JSON data in the request's context
ctx := context.WithValue(r.Context(), parsedJSONKey, data)
r = r.WithContext(ctx)
}
next.ServeHTTP(w, r) // Pass control to the next handler/middleware
})
}
// Middleware for URL-encoded form body parsing
func urlencodedFormParserMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost && r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" {
err := r.ParseForm() // This populates r.Form and r.PostForm
if err != nil {
log.Printf("Form parsing error: %v", err)
http.Error(w, "Bad form request: "+err.Error(), http.StatusBadRequest)
return
}
// No need to store in context, r.Form is already populated
}
next.ServeHTTP(w, r)
})
}
// jsonHandler now retrieves data from context
func jsonHandlerWithMiddleware(w http.ResponseWriter, r *http.Request) {
// Retrieve parsed data from context
parsedData, ok := r.Context().Value(parsedJSONKey).(MyJSONRequestBody)
if !ok {
// This should theoretically not happen if middleware is set up correctly
// or if the request didn't match the middleware's conditions.
http.Error(w, "JSON data not available or invalid context type", http.StatusInternalServerError)
return
}
fmt.Printf("Received JSON from middleware: Name='%s', Value=%d\n", parsedData.Name, parsedData.Value)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"message": "JSON received via middleware successfully"})
}
// formHandler now just accesses r.PostForm directly
func formHandlerWithMiddleware(w http.ResponseWriter, r *http.Request) {
// r.ParseForm() was called by the middleware, so r.PostForm is ready
firstName := r.PostForm.Get("firstName")
lastName := r.PostForm.Get("lastName")
fmt.Printf("Received Form from middleware: FirstName='%s', LastName='%s'\n", firstName, lastName)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"message": "Form data received via middleware successfully"})
}
func defaultHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, Go Web with Mux and Middleware!")
}
func main() {
router := mux.NewRouter()
// Apply middleware globally to all routes
router.Use(jsonBodyParserMiddleware)
router.Use(urlencodedFormParserMiddleware) // Equivalent to app.use(bodyParser.urlencoded()) and app.use(bodyParser.json())
// Define routes
router.HandleFunc("/", defaultHandler).Methods("GET")
router.HandleFunc("/submit-json", jsonHandlerWithMiddleware).Methods("POST")
router.HandleFunc("/submit-form", formHandlerWithMiddleware).Methods("POST")
log.Println("Server starting on :8080 (gorilla/mux)...")
log.Fatal(http.ListenAndServe(":8080", router))
}
/*
To test this:
1. Save as `main.go`.
2. Run `go mod init myapp` (if not already in a module)
3. Run `go get github.com/gorilla/mux`
4. Run `go run main.go`
Test with curl (same as above):
JSON POST:
curl -X POST -H "Content-Type: application/json" -d '{"name": "Alice", "value": 123}' http://localhost:8080/submit-json
Form POST:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'firstName=John&lastName=Doe' http://localhost:8080/submit-form
GET:
curl http://localhost:8080/
*/
Explanation for gorilla/mux:
mux.NewRouter(): Creates a new Mux router.
router.Use(middlewareFunction): This is the direct equivalent of app.use(). It registers middleware that will be executed for every incoming request.
- Middleware Structure: Go HTTP middleware typically follows the
func(http.Handler) http.Handler signature. It wraps the next handler (or middleware) and calls next.ServeHTTP(w, r) to pass control.
r.Context() and context.WithValue(): Because r.Body (the request body io.Reader) can only be read once, if middleware reads it, the handler won't be able to. The common Go pattern to pass data from middleware to a handler is to store it in the request's context.Context. You then create a new request with the updated context (r.WithContext(ctx)) and pass that down the chain.
r.ParseForm() vs. Context: For application/x-www-form-urlencoded or multipart/form-data, r.ParseForm() (or r.ParseMultipartForm()) modifies the http.Request directly by populating r.Form and r.PostForm. So, you don't need to put these into context; the handler can just access r.PostForm.Get().
Key Differences and Considerations:
- Explicitness: Go generally requires more explicit handling. You directly interact with
io.Reader for the body and encoding/json or r.ParseForm() for parsing. Express's req.body is a convenient abstraction.
r.Body is a Stream: r.Body is an io.ReadCloser. Once you read from it, the data is consumed. If you need to read it multiple times (e.g., in multiple middleware), you must read it once, store it (e.g., in a bytes.Buffer), and then replace r.Body with a new io.ReadCloser from the buffer, or pass the parsed data via context.Context. The context.Context approach is generally preferred for passing data.
- Error Handling: In Go, you typically handle errors immediately and return an
http.Error (which sends an HTTP status code and message). Express often relies on next(err) to pass errors down a middleware chain.
- Framework vs. Standard Library: Express is a framework. Go's
net/http is a robust standard library. While routers like gorilla/mux or chi add framework-like features, they are often built on top of net/http.
Choose the approach that best fits your project's needs:
- For smaller, simpler APIs or if you want minimal dependencies, the standard library (
net/http) approach (parsing in handlers) is perfectly fine and often preferred by experienced Gophers.
- For larger applications where you want more structured routing, middleware chaining, and a more Express-like development experience, a router like
gorilla/mux or chi is a good choice.