diff options
| author | Eltrac <hi@guhub.cn> | 2025-11-27 11:13:47 +0800 |
|---|---|---|
| committer | Eltrac <hi@guhub.cn> | 2025-11-27 11:13:47 +0800 |
| commit | 2447724fe676bff78e31e0c245b65e1f1608010e (patch) | |
| tree | 6246a7b6a8aacf6d3c2750dc52cdfb8549903e5f /context.go | |
| parent | 5e49bd23b5d9622db58f0aab129969ffc27bb935 (diff) | |
feat: add context methods that write responses fast
Diffstat (limited to 'context.go')
| -rw-r--r-- | context.go | 40 |
1 files changed, 40 insertions, 0 deletions
@@ -1,7 +1,9 @@ package growel import ( + "encoding/json" "net/http" + "strconv" ) type Context struct { @@ -10,4 +12,42 @@ type Context struct { Params map[string]string } +func (c *Context) Plain(code int, data string) { + c.W.Header().Set("Content-Type", "text/plain; charset=utf-8") + c.W.WriteHeader(code) + c.W.Write([]byte(data)) +} + +func (c *Context) JSON(code int, data any) { + c.W.Header().Set("Content-Type", "application/json; charset=utf-8") + c.W.WriteHeader(code) + + enc := json.NewEncoder(c.W) + _ = enc.Encode(data) +} + +func (c *Context) Error(code int, msg string) { + c.JSON(code, map[string]string{ + "error": http.StatusText(code), + "message": msg, + "status": strconv.Itoa(code), + }) +} + +func (c *Context) NotFound(msg string) { + c.Error(http.StatusNotFound, msg) +} + +func (c *Context) BadRequest(msg string) { + c.Error(http.StatusBadRequest, msg) +} + +func (c *Context) Unauthorized(msg string) { + c.Error(http.StatusUnauthorized, msg) +} + +func (c *Context) InternalError(msg string) { + c.Error(http.StatusInternalServerError, msg) +} + type Handler func(c *Context) |
