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)
}