From 054f9b22b0f72b703f3f05434a026b280a6692ae Mon Sep 17 00:00:00 2001 From: Eltrac Date: Wed, 3 Dec 2025 16:10:50 +0800 Subject: feat: provide basic data getters - c.Query(), from URL query string - c.PostFormValue(), from POST form - c.FormValue(), from both URL query and POST form - c.BindJSON(), from request body --- context.go | 34 +++++++++++++++++++++++++++++++++- engine.go | 8 ++++++++ types.go | 1 + 3 files changed, 42 insertions(+), 1 deletion(-) diff --git a/context.go b/context.go index 6241179..a364e5d 100644 --- a/context.go +++ b/context.go @@ -80,7 +80,7 @@ func (c *Context) InternalError(msg string) { c.Error(http.StatusInternalServerError, msg) } -/* Cookies */ +/* === Cookies === */ func (c *Context) Cookies() []*http.Cookie { return c.R.Cookies() @@ -111,3 +111,35 @@ func (c *Context) SetCookie(name string, value string) { } c.SetCompleteCookie(&cookie) } + +/* === Request Data === */ + +// Context.FormValue gets value from request form +// form contains URL querys and POST Form value +// +// alias of 'c.Form[key]` +func (c *Context) FormValue(key string) string { + return c.Form.Get(key) +} + +// Context.PostFormValue works similarly to Context.FormValue +// but it does NOT contain URL querys, only POST form +func (c *Context) PostFormValue(key string) string { + return c.R.PostFormValue(key) +} + +// Context.Query gets value from request URL query +// +// alias of 'c.Querys[key]' +func (c *Context) Query(key string) string { + return c.Querys.Get(key) +} + +// Context.BindJSON takes the container for JSON data +// decodes request body and then writes data to container +func (c *Context) BindJSON(v any) error { + c.R.Body = http.MaxBytesReader(c.W, c.R.Body, 2<<20) + dec := json.NewDecoder(c.R.Body) + dec.DisallowUnknownFields() + return dec.Decode(v) +} diff --git a/engine.go b/engine.go index 6fc1060..4d44fa1 100644 --- a/engine.go +++ b/engine.go @@ -38,11 +38,19 @@ func (a *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) { http.NotFound(w, req) return } + + err := req.ParseForm() + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + handler(&Context{ W: w, R: req, Params: params, Querys: req.URL.Query(), + Form: req.Form, }) } diff --git a/types.go b/types.go index 36e4f13..93f1487 100644 --- a/types.go +++ b/types.go @@ -10,6 +10,7 @@ type Context struct { R *http.Request Params map[string]string Querys url.Values + Form url.Values } type Handler func(c *Context) -- cgit v1.2.3