Method-based subrouting matches a shared path and selects request logic by HTTP method. In Go, register separate handlers such as GET /comments and POST /comments with net/http. section 8.1.1
Comments endpoint
A comments endpoint can serve existing comments with GET and append a submitted comment with POST. Requests using another method receive 405 Method Not Allowed; curl can exercise the POST route. section 8.1.1
Listing 8.1 Using built-in method routing
package main
import (
"net/http"
)
func getComments(w http.ResponseWriter,
r *http.Request) { #1
w.Write([]byte("here you'll get the comments"))
}
func postComments(w http.ResponseWriter,
r *http.Request) { #2
w.Write([]byte("thank you for posting a comment"))
}
func main() {
http.HandleFunc("GET /comments", getComments) #3
http.HandleFunc("POST /comments", postComments) #4
if err := http.ListenAndServe(":8000", nil); err != nil {
panic(err)
}
}
Use the complete net/http example to register distinct GET and POST handlers for the same /comments path and run the server on port 8000. section 8.1.1
Manual dispatch remains useful when method handling needs additional decisions:
- Inspect r.Method, read and decode a POST body, then choose creation or update logic based on the decoded identifier. section 8.1.1
- Consider OPTIONS responses when an endpoint should advertise its supported methods, and return explanatory error text where useful. section 8.1.1
