Skip to content

Commit 9be7a99

Browse files
committed
context
1 parent 45448cc commit 9be7a99

File tree

1 file changed

+69
-2
lines changed

1 file changed

+69
-2
lines changed

context.go

Lines changed: 69 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
package godzilla
22

3-
import "github.com/valyala/fasthttp"
3+
import (
4+
"fmt"
5+
"strings"
6+
7+
jsoniter "github.com/json-iterator/go"
8+
"github.com/valyala/fasthttp"
9+
)
410

511
const (
612
MimeApplicationJSON = "application/json"
@@ -45,11 +51,72 @@ func (ctx *context) Param(key string) string {
4551
return ctx.paramValues[key]
4652
}
4753

48-
func (ctx *context) Context() *fasthttp.Request {
54+
func (ctx *context) Context() *fasthttp.RequestCtx {
4955
return ctx.requestCtx
5056
}
5157

5258
func (ctx *context) SendBytes(value []byte) Context {
5359
ctx.requestCtx.Response.SetBodyRaw(value)
5460
return ctx
5561
}
62+
63+
func (ctx *context) SendString(value string) Context {
64+
ctx.requestCtx.SetBodyString(value)
65+
return ctx
66+
}
67+
68+
func (ctx *context) SendJSON(in interface{}) error {
69+
json := jsoniter.ConfigCompatibleWithStandardLibrary
70+
raw, err := json.Marshal(in)
71+
72+
if err != nil {
73+
return err
74+
}
75+
76+
ctx.requestCtx.Response.Header.SetContentType(MimeApplicationJSON)
77+
ctx.requestCtx.Response.SetBodyRaw(raw)
78+
79+
return nil
80+
}
81+
82+
func (ctx *context) Status(status int) Context {
83+
ctx.requestCtx.Response.SetStatusCode(status)
84+
return ctx
85+
}
86+
87+
func (ctx *context) Get(key string) string {
88+
return GetString(ctx.requestCtx.Request.Header.Peek(key))
89+
}
90+
91+
func (ctx *context) Set(key, value string) {
92+
ctx.requestCtx.Response.Header.Set(key, value)
93+
}
94+
95+
func (ctx *context) Query(key string) string {
96+
return GetString(ctx.requestCtx.QueryArgs().Peek(key))
97+
}
98+
99+
func (ctx *context) Body() string {
100+
return GetString(ctx.requestCtx.Request.Body())
101+
}
102+
103+
func (ctx *context) SetLocal(key string, value interface{}) {
104+
ctx.requestCtx.SetUserValue(key, value)
105+
}
106+
107+
func (ctx *context) GetLocal(key string) interface{} {
108+
return ctx.requestCtx.UserValue(key)
109+
}
110+
111+
func (ctx *context) ParseBody(out interface{}) error {
112+
contentType := GetString(ctx.requestCtx.Request.Header.ContentType())
113+
if strings.HasPrefix(contentType, MimeApplicationJSON) {
114+
json := jsoniter.ConfigCompatibleWithStandardLibrary
115+
return json.Unmarshal(ctx.requestCtx.Request.Body(), out)
116+
}
117+
118+
return fmt.Errorf("content type '%s' is not supported, "+
119+
"please open a request to support it "+
120+
"(https://github.com/godzillaframework//godzilla/issues",
121+
contentType)
122+
}

0 commit comments

Comments
 (0)