REST APIs
suggest changeBuilding RESTful APIs is one of the most common applications of Go. With high concurrency support, small memory footprint, and the powerful net/http package in the standard library, Go is exceptionally well-suited for high-throughput HTTP microservices.
Since Go 1.22, the standard http.ServeMux natively supports HTTP methods (e.g., GET, POST, DELETE) and path wildcards (e.g., /api/tasks/{id}), eliminating the need for third-party routers in many applications.
1. Modern Routing with Go 1.22+ http.ServeMux
The standard library router matches patterns formatted as "[METHOD ]path":
mux := http.NewServeMux()
// Method-specific routing
mux.HandleFunc("GET /api/tasks", handleListTasks)
mux.HandleFunc("POST /api/tasks", handleCreateTask)
// Parameterized path routing with wildcards
mux.HandleFunc("GET /api/tasks/{id}", handleGetTask)
mux.HandleFunc("PUT /api/tasks/{id}", handleUpdateTask)
mux.HandleFunc("DELETE /api/tasks/{id}", handleDeleteTask)
Inside handlers, extract path variables using r.PathValue("id").
2. Reusable JSON Response Helper
Standardizing JSON responses and error messages ensures consistent API contracts:
package main
import (
"encoding/json"
"net/http"
)
// respondJSON serializes data as JSON and sets the HTTP status code
func respondJSON(w http.ResponseWriter, status int, data any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
if data != nil {
_ = json.NewEncoder(w).Encode(data)
}
}
// respondError formats errors in a standard JSON envelope
func respondError(w http.ResponseWriter, status int, message string) {
respondJSON(w, status, map[string]string{"error": message})
}
3. Safe JSON Request Decoding
To protect against denial-of-service via oversized request payloads and catch unrecognized JSON keys:
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) error {
// Limit request body size to 1 MB
r.Body = http.MaxBytesReader(w, r.Body, 1048576)
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields() // Reject unexpected JSON keys
if err := dec.Decode(dst); err != nil {
return err
}
return nil
}
4. Complete RESTful CRUD Service Example
Here is a complete, runnable REST API managing a task list using thread-safe state (it uses the respondJSON, respondError and decodeJSON helpers from sections 2 and 3, placed in the same package):
package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"sync"
"time"
)
type Task struct {
ID int `json:"id"`
Title string `json:"title"`
Completed bool `json:"completed"`
CreatedAt time.Time `json:"created_at"`
}
type TaskStore struct {
mu sync.RWMutex
tasks map[int]Task
nextID int
}
func NewTaskStore() *TaskStore {
return &TaskStore{
tasks: make(map[int]Task),
nextID: 1,
}
}
// Global store
var store = NewTaskStore()
// GET /api/tasks
func listTasks(w http.ResponseWriter, r *http.Request) {
store.mu.RLock()
defer store.mu.RUnlock()
tasks := make([]Task, 0, len(store.tasks))
for _, task := range store.tasks {
tasks = append(tasks, task)
}
respondJSON(w, http.StatusOK, tasks)
}
// POST /api/tasks
func createTask(w http.ResponseWriter, r *http.Request) {
var input struct {
Title string `json:"title"`
}
if err := decodeJSON(w, r, &input); err != nil {
respondError(w, http.StatusBadRequest, "Invalid request body: "+err.Error())
return
}
if input.Title == "" {
respondError(w, http.StatusUnprocessableEntity, "Title is required")
return
}
store.mu.Lock()
task := Task{
ID: store.nextID,
Title: input.Title,
Completed: false,
CreatedAt: time.Now().UTC(),
}
store.tasks[task.ID] = task
store.nextID++
store.mu.Unlock()
w.Header().Set("Location", fmt.Sprintf("/api/tasks/%d", task.ID))
respondJSON(w, http.StatusCreated, task)
}
// GET /api/tasks/{id}
func getTask(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
respondError(w, http.StatusBadRequest, "Invalid task ID")
return
}
store.mu.RLock()
task, exists := store.tasks[id]
store.mu.RUnlock()
if !exists {
respondError(w, http.StatusNotFound, "Task not found")
return
}
respondJSON(w, http.StatusOK, task)
}
// PUT /api/tasks/{id}
func updateTask(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
respondError(w, http.StatusBadRequest, "Invalid task ID")
return
}
var input struct {
Title *string `json:"title"`
Completed *bool `json:"completed"`
}
if err := decodeJSON(w, r, &input); err != nil {
respondError(w, http.StatusBadRequest, "Invalid request body: "+err.Error())
return
}
store.mu.Lock()
defer store.mu.Unlock()
task, exists := store.tasks[id]
if !exists {
respondError(w, http.StatusNotFound, "Task not found")
return
}
if input.Title != nil {
task.Title = *input.Title
}
if input.Completed != nil {
task.Completed = *input.Completed
}
store.tasks[id] = task
respondJSON(w, http.StatusOK, task)
}
// DELETE /api/tasks/{id}
func deleteTask(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
respondError(w, http.StatusBadRequest, "Invalid task ID")
return
}
store.mu.Lock()
_, exists := store.tasks[id]
if exists {
delete(store.tasks, id)
}
store.mu.Unlock()
if !exists {
respondError(w, http.StatusNotFound, "Task not found")
return
}
w.WriteHeader(http.StatusNoContent)
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /api/tasks", listTasks)
mux.HandleFunc("POST /api/tasks", createTask)
mux.HandleFunc("GET /api/tasks/{id}", getTask)
mux.HandleFunc("PUT /api/tasks/{id}", updateTask)
mux.HandleFunc("DELETE /api/tasks/{id}", deleteTask)
server := &http.Server{
Addr: ":8080",
Handler: mux,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
}
fmt.Println("REST API server listening on http://localhost:8080")
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
fmt.Printf("Server error: %v\n", err)
}
}
5. Production Middleware: Logging and Panics
Wrap handlers with standard middleware to catch runtime panics and log HTTP requests:
func LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
fmt.Printf("[%s] %s - %v\n", r.Method, r.URL.Path, time.Since(start))
})
}
func RecoveryMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
respondError(w, http.StatusInternalServerError, "Internal server error")
}
}()
next.ServeHTTP(w, r)
})
}
Best Practices
- Always Set Server Timeouts: Always configure
ReadTimeout,WriteTimeout, andIdleTimeoutonhttp.Serverto prevent slow-loris attacks and connection resource exhaustion. - Limit Request Body Sizes: Use
http.MaxBytesReaderto avoid memory exhaustion from oversized request bodies. - Use Proper HTTP Status Codes: Return
201 Createdfor successful resource creations,204 No Contentfor deletions, and422 Unprocessable Entityor400 Bad Requestfor invalid input.