/
encode.go
96 lines (79 loc) · 2.17 KB
/
encode.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package transport_http
import (
"context"
"io"
"io/ioutil"
"net/http"
"reflect"
"github.com/johnnyeven/libtools/courier"
"github.com/johnnyeven/libtools/courier/httpx"
"github.com/johnnyeven/libtools/courier/status_error"
"github.com/johnnyeven/libtools/courier/transport_http/transform"
)
func setContextType(w http.ResponseWriter, s string) {
w.Header().Set(httpx.HeaderContentType, s+";charset=utf-8")
}
func encodeHttpResponse(_ context.Context, w http.ResponseWriter, r *http.Request, response interface{}) error {
if redirect, ok := response.(httpx.IRedirect); ok {
http.Redirect(w, r, redirect.Redirect(r.Host), redirect.Status())
return nil
}
if hasMeta, ok := response.(courier.IMeta); ok {
meta := hasMeta.Meta()
for k := range meta {
w.Header().Set(k, meta.Get(k))
}
}
code := http.StatusOK
if r.Method == http.MethodPost {
code = http.StatusCreated
}
if sc, ok := response.(IStatus); ok {
code = sc.Status()
}
if response == nil {
code = http.StatusNoContent
}
if code == http.StatusNoContent {
w.WriteHeader(code)
return nil
}
tpe := reflect.TypeOf(response)
for tpe.Kind() == reflect.Ptr {
tpe = tpe.Elem()
}
contentType := ""
if withContentType, ok := response.(IContentType); ok {
contentType = withContentType.ContentType()
setContextType(w, contentType)
}
if reader, ok := response.(io.Reader); ok {
b, errForRead := ioutil.ReadAll(reader)
if errForRead != nil {
return errForRead
}
w.WriteHeader(code)
w.Write(b)
return nil
}
if contentType == "" {
contentType = httpx.MIMEJSON
setContextType(w, contentType)
}
dataList, err := transform.ContentMarshal(reflect.ValueOf(response), "body", contentType)
if err != nil {
return err
}
w.WriteHeader(code)
w.Write(dataList[0])
return nil
}
func encodeHttpError(c context.Context, w http.ResponseWriter, r *http.Request, err error) (finalErr error) {
if redirect, ok := err.(httpx.IRedirect); ok {
http.Redirect(w, r, redirect.Redirect(r.Host), redirect.Status())
return nil
}
finalStatusErr := status_error.FromError(err).WithSource(c.Value(ContextKeyServerName).(string))
encodeHttpResponse(c, w, r, finalStatusErr)
return finalStatusErr
}