How to Return JSON Responses from a Go HTTP Server

Web
Set Content-Type to application/json and use json.NewEncoder to write data for JSON responses in Go.

Set the response Content-Type to application/json and write the JSON-encoded data to the response writer using json.NewEncoder. This ensures the client receives a valid JSON payload with the correct headers.

package main

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

type Response struct {
	Message string `json:"message"`
}

func handler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(Response{Message: "Hello, World!"})
}

func main() {
	http.HandleFunc("/api", handler)
	http.ListenAndServe(":8080", nil)
}