Backend Boilerplates go Beginner

Go JSON HTTP Helpers

Two tiny helpers for consistent JSON responses in Go net/http handlers.

go
package web

import (
    "encoding/json"
    "net/http"
)

func JSON(w http.ResponseWriter, status int, v any) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(status)
    _ = json.NewEncoder(w).Encode(v)
}

func Err(w http.ResponseWriter, status int, msg string) {
    JSON(w, status, map[string]string{"error": msg})
}

Prerequisites

  • Go >= 1.21

Pro Tips

  • → Pass a struct pointer to leverage omitempty tags.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
go
Level
Beginner
Read time
2 min
Published
Jun 2024
License
Commercial License

Newsletter

New modules every week, directly to your inbox.