Building REST APIs with Go
Build production-ready REST APIs using Go and Chi router. Middleware, routing, and best practices.
Go’s standard library is powerful enough for most HTTP servers, but Chi adds conveniences for real applications.
Setup
go mod init myapi
go get github.com/go-chi/chi/v5
Basic Server
package main
import (
"encoding/json"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
func main() {
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
})
http.ListenAndServe(":8080", r)
}
RESTful Routes
r.Route("/api/v1/users", func(r chi.Router) {
r.Get("/", listUsers)
r.Post("/", createUser)
r.Get("/{id}", getUser)
r.Put("/{id}", updateUser)
r.Delete("/{id}", deleteUser)
})
JSON Response Helper
func respondJSON(w http.ResponseWriter, status int, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(data)
}
Best Practices
- Version your API (
/api/v1/...) - Use proper HTTP status codes
- Validate input data
- Handle errors consistently
- Add request timeouts