-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathencoder.go
More file actions
63 lines (52 loc) · 1.75 KB
/
encoder.go
File metadata and controls
63 lines (52 loc) · 1.75 KB
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
package hyperdrive
import (
"encoding/json"
"encoding/xml"
"errors"
"net/http"
"strings"
)
// ContentEncoder interface wraps the details of encoding response bodies to
// support automatic Content Negotiation.
type ContentEncoder interface {
Encode(interface{}) error
}
// NullEncoder is an implementation of ContentEncoder, and is the default
// encoder used when Content Negotiation has falied. It produces a 406
// NOT ACCEPTABLE error when it's Encode() function is run.
type NullEncoder struct{}
// Encode returns a 406 NOT ACCEPTABLE error.
func (enc NullEncoder) Encode(v interface{}) error {
return errors.New(http.StatusText(http.StatusNotAcceptable))
}
// JSONEncoder is an implementation of ContentEncoder and wraps the Encoder
// found in encoding/json package.
type JSONEncoder struct {
Encoder *json.Encoder
}
// Encode encodes input as json text or returns an error.
func (enc JSONEncoder) Encode(v interface{}) error {
return enc.Encoder.Encode(v)
}
// XMLEncoder is an implementation of ContentEncoder and wraps the Encoder
// found in encoding/xml package.
type XMLEncoder struct {
Encoder *xml.Encoder
}
// Encode encodes input as xml text or returns an error.
func (enc XMLEncoder) Encode(v interface{}) error {
return enc.Encoder.Encode(v)
}
// GetEncoder returns the correct ContentEncoder, determined by the Accept
// header, to support automatic Content Negotiation.
func GetEncoder(rw http.ResponseWriter, accept string) (ContentEncoder, http.ResponseWriter) {
if strings.HasSuffix(accept, "json") {
rw.Header().Set("Content-Type", accept)
return JSONEncoder{json.NewEncoder(rw)}, rw
}
if strings.HasSuffix(accept, "xml") {
rw.Header().Set("Content-Type", accept)
return XMLEncoder{xml.NewEncoder(rw)}, rw
}
return NullEncoder{}, rw
}