-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
123 lines (96 loc) · 2.32 KB
/
context.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
package gimlet
import (
"encoding/json"
"net/http"
"net/url"
"github.com/gorilla/schema"
"github.com/samuelbeaulieu1/gimlet/logger"
"github.com/samuelbeaulieu1/gimlet/responses"
)
type Context struct {
Request *http.Request
Params *ContextParams
Writer http.ResponseWriter
Engine *Engine
body url.Values
decoder *schema.Decoder
Authenticator
}
func NewContext(w http.ResponseWriter, r *http.Request, engine *Engine, cp *ContextParams) *Context {
ctx := &Context{
Writer: w,
Request: r,
Params: cp,
Engine: engine,
decoder: schema.NewDecoder(),
}
ctx.decoder.SetAliasTag("json")
ctx.parsePostForm()
return ctx
}
func (ctx *Context) parsePostForm() {
if err := ctx.Request.ParseMultipartForm(ctx.Engine.MaxPostFormSizeMB); err != nil {
if err != http.ErrNotMultipart {
logger.PrintError("Error parsing post form: %v", err)
}
}
ctx.body = ctx.Request.PostForm
}
func (ctx *Context) ParseBody(s any) bool {
var err error
if ctx.Request.Header.Get("Content-Type") == "application/json" {
err = json.NewDecoder(ctx.Request.Body).Decode(s)
} else {
err = ctx.decoder.Decode(s, ctx.body)
}
return err != nil
}
func (ctx *Context) GetBodyParam(key string) string {
if val := ctx.GetBodyParams(key); len(val) > 0 {
return val[0]
}
return ""
}
func (ctx *Context) GetBodyParams(key string) []string {
if val, ok := ctx.body[key]; ok {
return val
}
return []string{}
}
func (ctx *Context) GetParam(key string) string {
return ctx.Params.Get(key)
}
func (ctx *Context) Status(code int) {
ctx.Writer.WriteHeader(code)
}
func (ctx *Context) WriteMessage(res string) {
ctx.Writer.Write([]byte(res))
}
func (ctx *Context) SetJSONContent() {
ctx.Writer.Header().Set("Content-Type", "application/json")
}
func (ctx *Context) WriteError(code int, message ...string) {
ctx.SetJSONContent()
ctx.Status(code)
if len(message) > 0 {
ctx.WriteMessage(message[0])
}
}
func (ctx *Context) WriteJSON(data any) {
ctx.SetJSONContent()
json.NewEncoder(ctx.Writer).Encode(data)
}
func (ctx *Context) WriteJSONResponse(data any) {
ctx.SetJSONContent()
json.NewEncoder(ctx.Writer).Encode(&responses.RequestResponse{
Status: "success",
Data: data,
})
}
func (ctx *Context) WriteJSONError(code int, err ...any) {
ctx.SetJSONContent()
ctx.Status(code)
if len(err) > 0 {
ctx.WriteJSON(err[0])
}
}