forked from francoispqt/gojay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
72 lines (61 loc) · 1.21 KB
/
main.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
68
69
70
71
72
package main
import (
"net/http"
"github.com/francoispqt/gojay"
)
type message struct {
foo string
bar string
}
func (m *message) UnmarshalJSONObject(dec *gojay.Decoder, k string) error {
switch k {
case "foo":
return dec.AddString(&m.foo)
case "bar":
return dec.AddString(&m.bar)
}
return nil
}
func (m *message) NKeys() int {
return 2
}
func (m *message) MarshalJSONObject(dec *gojay.Encoder) {
dec.AddStringKey("foo", m.foo)
dec.AddStringKey("bar", m.bar)
}
func (m *message) IsNil() bool {
return m == nil
}
func home(w http.ResponseWriter, r *http.Request) {
// read body using io.Reader
m := &message{}
dec := gojay.BorrowDecoder(r.Body)
defer dec.Release()
err := dec.DecodeObject(m)
if err != nil {
i, err := w.Write([]byte(err.Error()))
if err != nil || i == 0 {
panic(err)
}
return
}
// just transform response slightly
m.foo += "hey"
// return response using io.Writer
enc := gojay.BorrowEncoder(w)
defer enc.Release()
err = enc.Encode(m)
if err != nil {
i, err := w.Write([]byte(err.Error()))
if err != nil || i == 0 {
panic(err)
}
}
return
}
func main() {
http.HandleFunc("/", home)
if err := http.ListenAndServe(":8080", nil); err != nil {
panic(err)
}
}