-
Notifications
You must be signed in to change notification settings - Fork 2
/
encoding.go
45 lines (36 loc) · 1.12 KB
/
encoding.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
package gofast
import (
"encoding/json"
"log"
"github.com/valyala/fasthttp"
)
type RequestEncoder func(req *fasthttp.Request, in interface{}) error
type ResponseDecoder func(resp *fasthttp.Response, out interface{}) error
var JSONEncoder = func(req *fasthttp.Request, in interface{}) error {
req.Header.SetContentType("application/json")
return json.NewEncoder(req.BodyWriter()).Encode(in)
}
var JSONDecoder = func(resp *fasthttp.Response, out interface{}) error {
if err := json.Unmarshal(resp.Body(), out); err != nil {
log.Printf("[gofast] response decode failed - code: %v, body: %v", resp.StatusCode(), string(resp.Body()))
return err
}
return nil
}
var URLEncoder = func(req *fasthttp.Request, in interface{}) error {
args := fasthttp.AcquireArgs()
defer fasthttp.ReleaseArgs(args)
for k, v := range in.(Body) {
args.Set(k, v)
}
if _, err := args.WriteTo(req.BodyWriter()); err != nil {
return err
}
req.Header.SetContentType("application/x-www-form-urlencoded")
return nil
}
var TextDecoder = func(resp *fasthttp.Response, out interface{}) error {
s := out.(*string)
*s = string(resp.Body())
return nil
}