forked from jchannon/negotiator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonprocessor.go
67 lines (53 loc) · 1.68 KB
/
jsonprocessor.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
62
63
64
65
66
67
package negotiator
import (
"encoding/json"
"net/http"
"strings"
)
const defaultJSONContentType = "application/json"
type jsonProcessor struct {
dense bool
prefix, indent string
contentType string
}
// NewJSON creates a new processor for JSON without indentation.
func NewJSON() ResponseProcessor {
return &jsonProcessor{true, "", "", defaultJSONContentType}
}
// NewJSONIndent creates a new processor for JSON with a specified indentation.
func NewJSONIndent(prefix, index string) ResponseProcessor {
return &jsonProcessor{false, prefix, index, defaultJSONContentType}
}
// NewJSONIndent2Spaces creates a new processor for JSON with 2-space indentation.
func NewJSONIndent2Spaces() ResponseProcessor {
return NewJSONIndent("", " ")
}
// Implements ContentTypeSettable for this type.
func (p *jsonProcessor) SetContentType(contentType string) ResponseProcessor {
p.contentType = contentType
return p
}
// Implements AjaxResponseProcessor for this type.
func (*jsonProcessor) IsAjaxResponder() bool {
return true
}
func (*jsonProcessor) CanProcess(mediaRange string) bool {
return strings.EqualFold(mediaRange, "application/json") ||
strings.HasPrefix(mediaRange, "application/json-") ||
strings.HasSuffix(mediaRange, "+json")
}
func (p *jsonProcessor) Process(w http.ResponseWriter, req *http.Request, dataModel interface{}, context ...interface{}) error {
if dataModel == nil {
w.WriteHeader(http.StatusNoContent)
return nil
}
w.Header().Set("Content-Type", p.contentType)
if p.dense {
return json.NewEncoder(w).Encode(dataModel)
}
js, err := json.MarshalIndent(dataModel, p.prefix, p.indent)
if err != nil {
return err
}
return writeWithNewline(w, js)
}