-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponse.go
44 lines (38 loc) · 958 Bytes
/
response.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
package rest
import (
"encoding/json"
"fmt"
"mime"
"net/http"
)
type Response interface {
Parse(resp *http.Response, result interface{}, opts ...func(*http.Response) error) error
}
type JsonResponse struct {
}
func (j JsonResponse) Parse(resp *http.Response, result interface{}, opts ...func(*http.Response) error) error {
for _, opt := range opts {
if err := opt(resp); err != nil {
return err
}
}
if resp.StatusCode == http.StatusNoContent || result == nil {
return nil
}
if err := j.checkContentType(resp.Header.Get("Content-Type")); err != nil {
return err
}
decoder := json.NewDecoder(resp.Body)
decoder.UseNumber()
return decoder.Decode(result)
}
func (j JsonResponse) checkContentType(contentType string) error {
mediaType, _, err := mime.ParseMediaType(contentType)
if err != nil {
return err
}
if mediaType != "application/json" {
return fmt.Errorf("can't parse content-type %s", contentType)
}
return nil
}