-
Notifications
You must be signed in to change notification settings - Fork 19
/
responses.go
48 lines (41 loc) · 1.1 KB
/
responses.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
package http
import (
"encoding/json"
routing "github.com/qiangxue/fasthttp-routing"
"io"
)
const (
jsonContentTypeHeader = "application/json"
)
// Response Response
type Response struct {
Code string `json:"code"`
Message string `json:"message"`
}
// NewResponse NewResponse
func NewResponse(code, msg string) Response {
return Response{
Code: code,
Message: msg,
}
}
// RespondMsg RespondMsg
func RespondMsg(c *routing.Context, httpCode int, code, msg string) {
resp := NewResponse(code, msg)
b, _ := json.Marshal(&resp)
Respond(c, httpCode, b)
}
// Respond Respond
func Respond(c *routing.Context, httpCode int, obj []byte) {
c.RequestCtx.Response.SetStatusCode(httpCode)
c.RequestCtx.Response.SetBody(obj)
if json.Valid(obj) {
c.RequestCtx.Response.Header.SetContentType(jsonContentTypeHeader)
}
}
// RespondStream RespondStream
// If bodySize < 0, then bodyStream is read until io.EOF.
func RespondStream(c *routing.Context, httpCode int, bodyStream io.Reader, bodySize int) {
c.RequestCtx.Response.SetStatusCode(httpCode)
c.RequestCtx.Response.SetBodyStream(bodyStream, bodySize)
}