forked from OneOfOne/gserv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resp.go
187 lines (158 loc) · 4.25 KB
/
resp.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
package gserv
import (
"bytes"
"encoding/json"
"fmt"
"io"
"mime"
"net/http"
"path/filepath"
"github.com/alpineiq/oerrs"
"github.com/alpineiq/otk"
)
// Common responses
var (
RespMethodNotAllowed Response = NewJSONErrorResponse(http.StatusMethodNotAllowed).Cached()
RespNotFound Response = NewJSONErrorResponse(http.StatusNotFound).Cached()
RespForbidden Response = NewJSONErrorResponse(http.StatusForbidden).Cached()
RespBadRequest Response = NewJSONErrorResponse(http.StatusBadRequest).Cached()
RespOK Response = NewJSONResponse("OK").Cached()
RespEmpty Response = CachedResponse(http.StatusNoContent, "", nil)
RespPlainOK Response = CachedResponse(http.StatusOK, "", nil)
RespRedirectRoot Response = Redirect("/", false)
// Break can be returned from a handler to break a handler chain.
// It doesn't write anything to the connection.
// if you reassign this, a wild animal will devour your face.
Break Response = &cachedResp{code: -1}
)
// Response represents a generic return type for http responses.
type Response interface {
Status() int
WriteToCtx(ctx *Context) error
}
func PlainResponse(contentType string, body any) Response {
return CachedResponse(http.StatusOK, contentType, body)
}
func CachedResponse(code int, contentType string, body any) Response {
if body == nil && code != http.StatusNoContent {
body = http.StatusText(code)
}
var b []byte
switch v := body.(type) {
case nil:
case []byte:
b = v
case string:
b = otk.UnsafeBytes(v)
case fmt.Stringer:
b = otk.UnsafeBytes(v.String())
case io.Reader:
var buf bytes.Buffer
io.Copy(&buf, v)
b = buf.Bytes()
default:
v = otk.UnsafeBytes(fmt.Sprintf("%v", v))
}
return &cachedResp{
ct: contentType,
body: b,
code: code,
}
}
type cachedResp struct {
ct string
body []byte
code int
}
func (r *cachedResp) Status() int { return r.code }
func (r *cachedResp) WriteToCtx(ctx *Context) error {
if r.ct != "" {
ctx.SetContentType(r.ct)
}
if r.code != 0 {
ctx.WriteHeader(r.code)
}
_, err := ctx.Write(r.body)
return err
}
func (r *cachedResp) MarshalJSON() ([]byte, error) {
return r.body, nil
}
func (r *cachedResp) MarshalMsgPack() ([]byte, error) {
return r.body, nil
}
func (r *cachedResp) Cached() Response { return r }
// ReadJSONResponse reads a response from an io.ReadCloser and closes the body.
// dataValue is the data type you're expecting, for example:
//
// r, err := ReadJSONResponse(res.Body, &map[string]*Stats{})
func ReadJSONResponse(rc io.ReadCloser, dataValue any) (r *JSONResponse, err error) {
defer rc.Close()
r = &JSONResponse{
Data: dataValue,
}
if err = json.NewDecoder(rc).Decode(r); err != nil {
return
}
if r.Success {
return
}
var me MultiError
for _, v := range r.Errors {
me.Push(&v)
}
if err = me.Err(); err == nil {
err = oerrs.String(http.StatusText(r.Code))
}
return
}
func JSONRequest(method, url string, reqData, respData any) (err error) {
return otk.Request(method, "", url, reqData, func(r *http.Response) error {
_, err := ReadJSONResponse(r.Body, respData)
return err
})
}
// Redirect returns a redirect Response.
// if perm is false it uses http.StatusFound (302), otherwise http.StatusMovedPermanently (302)
func Redirect(url string, perm bool) Response {
code := http.StatusFound
if perm {
code = http.StatusMovedPermanently
}
return RedirectWithCode(url, code)
}
// RedirectWithCode returns a redirect Response with the specified status code.
func RedirectWithCode(url string, code int) Response {
return redirResp{url, code}
}
type redirResp struct {
url string
code int
}
func (r redirResp) Status() int { return r.code }
func (r redirResp) WriteToCtx(ctx *Context) error {
if r.url == "" {
return ErrInvalidURL
}
http.Redirect(ctx, ctx.Req, r.url, r.code)
return nil
}
// File returns a file response.
// example: return File("plain/html", "index.html")
func File(contentType, fp string) Response {
if contentType == "" {
contentType = mime.TypeByExtension(filepath.Ext(fp))
}
return fileResp{contentType, fp}
}
type fileResp struct {
ct string
fp string
}
func (f fileResp) Status() int { return 0 }
func (f fileResp) WriteToCtx(ctx *Context) error {
if f.ct != "" {
ctx.SetContentType(f.ct)
}
return ctx.File(f.fp)
}