/
response.go
75 lines (58 loc) · 1.43 KB
/
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
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
package middleware
import "net/http"
import "github.com/gin-gonic/gin"
type Response interface {
Ok(value string)
Error(status int, value string)
Created()
NoContent()
Status(code int) Entity
Header(headers Params) Header
}
type Header interface {
Status(code int) Entity
}
type Entity interface {
Entity(value interface{})
}
type responseBuild struct {
ctx *gin.Context
}
type entityBuild struct {
status int
build *responseBuild
}
type headerBuild struct {
build *responseBuild
}
type Params map[string]string
func NewResponse(c *gin.Context) Response {
return &responseBuild{ctx: c}
}
func (r *responseBuild) Error(status int, value string) {
r.ctx.Data(status, "application/json", []byte(value))
}
func (r *responseBuild) Ok(value string) {
r.ctx.Data(http.StatusOK, "application/json", []byte(value))
}
func (r *responseBuild) Created() {
r.ctx.JSON(http.StatusCreated, gin.H{})
}
func (r *responseBuild) NoContent() {
r.ctx.Writer.WriteHeader(http.StatusNoContent)
}
func (r *responseBuild) Status(code int) Entity {
return &entityBuild{status: code, build: r}
}
func (r *responseBuild) Header(headers Params) Header {
for key, value := range headers {
r.ctx.Writer.Header().Add(key, value)
}
return &headerBuild{build: r}
}
func (e *headerBuild) Status(code int) Entity {
return &entityBuild{status: code, build: e.build}
}
func (e *entityBuild) Entity(value interface{}) {
e.build.ctx.JSON(e.status, value)
}