-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhttp_response_writer.go
61 lines (47 loc) · 1.33 KB
/
http_response_writer.go
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"github.com/jsightapi/jsight-api-core/catalog"
)
type httpResponseWriter struct {
writer http.ResponseWriter
}
func (r httpResponseWriter) jdocJSON(b []byte) {
r.writer.Header().Set("X-Jdoc-Exchange-Version", catalog.JDocExchangeVersion)
r.json(b)
}
func (r httpResponseWriter) json(b []byte) {
r.writer.Header().Set("Content-Type", "application/json; charset=utf-8")
n, _ := r.writer.Write(b)
log.Printf("... Ok (%d bytes)", n)
}
func (r httpResponseWriter) yaml(b []byte) {
r.writer.Header().Set("Content-Type", "application/yaml; charset=utf-8")
n, _ := r.writer.Write(b)
log.Printf("... Ok (%d bytes)", n)
}
func (r httpResponseWriter) errorStr(s string) {
r.error(errors.New(s))
}
func (r httpResponseWriter) error(e error) {
info := newErrorInfo(e)
b, err := json.Marshal(info)
if err != nil {
r.internalServerError(err)
return
}
r.writer.Header().Set("Content-Type", "application/json; charset=utf-8")
r.writer.WriteHeader(http.StatusConflict)
_, _ = r.writer.Write(b)
log.Print("... " + e.Error())
}
func (r httpResponseWriter) internalServerError(e error) {
r.writer.Header().Set("Content-Type", "text/plain")
r.writer.WriteHeader(http.StatusInternalServerError)
_, _ = fmt.Fprint(r.writer, e.Error())
log.Print("... " + e.Error())
}