respond.go

 1package responder
 2
 3import (
 4	"encoding/json"
 5	"net/http"
 6)
 7
 8type defaultResponse struct {
 9	Status  int    `json:"status"`
10	Message string `json:"message"`
11}
12
13type response struct {
14	value  *interface{}
15	status int
16	pretty bool
17}
18
19type Option func(r *response)
20
21func Pretty(pretty bool) Option {
22	return func(r *response) {
23		r.pretty = pretty
24	}
25}
26
27func Status(status int) Option {
28	return func(r *response) {
29		r.status = status
30	}
31}
32
33func Body(v interface{}) Option {
34	return func(r *response) {
35		r.value = &v
36	}
37}
38
39func Respond(w http.ResponseWriter, opts ...Option) {
40	r := &response{
41		status: http.StatusOK,
42	}
43
44	for _, opt := range opts {
45		opt(r)
46	}
47
48	enc := json.NewEncoder(w)
49
50	if r.pretty {
51		enc.SetIndent("    ", "")
52	}
53
54	w.Header().Add("Content-Type", "application/json")
55	w.WriteHeader(r.status)
56
57	if v := r.value; v != nil {
58		_ = enc.Encode(*v)
59	} else {
60		_ = enc.Encode(&defaultResponse{
61			Status:  r.status,
62			Message: http.StatusText(r.status),
63		})
64	}
65}