REST
REST in a Go service means resources as URLs, HTTP methods as verbs, JSON as the body, and status codes as outcomes. net/http does not include a REST framework; you map paths on a mux and write handlers.
Detailed Explanation
GET /users/{id} returns a user. POST /users creates one. DELETE /users/{id} removes one. The same handler type, different methods. Go 1.22's ServeMux patterns encode that: mux.HandleFunc("GET /users/{id}", get) and mux.HandleFunc("POST /users", create).
JSON in and out. Decode the body into a struct (not map[string]any if you can help it). Validate. Call a store. Encode a response struct. Set Content-Type: application/json. That loop is the REST handler.
Status codes are the result type. 201 with a Location header after create. 204 on a successful delete with no body. 400 for a bad body, 404 for a missing id, 409 for a conflict, 500 for an unexpected store error. Do not put "error": true in a 200 body as the only signal.
Idempotency. PUT and DELETE should be safe to retry. POST often is not. If you accept POST retries, use an idempotency key the store understands.
What it costs. A few handlers and a mux are enough for a small API. When you have fifty resources, a tiny helper for decode/encode/status reduces copy-paste. A full framework is optional. Keep SQL and HTTP in different packages so REST stays a translation layer.
Code Examples
package main
import (
"encoding/json"
"net/http"
)
func getUser(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if id == "" {
http.Error(w, "missing id", http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"id": id})
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /users/{id}", getUser)
http.ListenAndServe(":8080", mux)
}Common Gotchas
`http.Error` writes text/plain
for JSON APIs write your own error body and status.
REST is not a package
this term is the mapping convention.
`POST` that is not idempotent will duplicate rows on client retry
`POST` that is not idempotent will duplicate rows on client retry