-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.go
More file actions
41 lines (36 loc) · 903 Bytes
/
http.go
File metadata and controls
41 lines (36 loc) · 903 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/pkg/errors"
"net/http"
"os"
)
func respond(w http.ResponseWriter, r *http.Request, v interface{}, code int) {
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(v)
if err != nil {
respondErr(w, r, err, http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(code)
_, err = buf.WriteTo(w)
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", errors.Wrap(err, "respond"))
}
}
func respondErr(w http.ResponseWriter, r *http.Request, err error, code int) {
errObj := struct {
Error string `json:"error"`
}{
Error: err.Error(),
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(code)
err = json.NewEncoder(w).Encode(errObj)
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", errors.Wrap(err, "respondErr"))
}
}