diff options
| author | Eltrac <hi@guhub.cn> | 2025-12-02 16:06:35 +0800 |
|---|---|---|
| committer | Eltrac <hi@guhub.cn> | 2025-12-02 16:06:35 +0800 |
| commit | 6ae235c31129190ed54e33b99f20deecc051ac04 (patch) | |
| tree | 33e7b92268d5286fbfe3cfaf95ea75db42c123d4 /context.go | |
| parent | 3f53ba50f2e562b5a2bc97442266b5e7acd585eb (diff) | |
style(context.go): add doc comments
Diffstat (limited to 'context.go')
| -rw-r--r-- | context.go | 28 |
1 files changed, 28 insertions, 0 deletions
@@ -6,12 +6,18 @@ import ( "strconv" ) +// Plain writes plain text to ResponseWriter +// with code and string passed as parameters +// this automatically sets Content-Type to "text/plain; charset=utf-8" 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)) } +// JSON receives a map or struct and converts it to JSON +// then writes it to ResponseWriter with code passed as parameter +// this automatically sets Content-Type to "application/json; charset=utf-8" func (c *Context) JSON(code int, data any) { c.W.Header().Set("Content-Type", "application/json; charset=utf-8") c.W.WriteHeader(code) @@ -20,6 +26,20 @@ func (c *Context) JSON(code int, data any) { _ = enc.Encode(data) } +// XML is unfinished and works almost the same as Plain() +// but it sets Content-Type to "application/xml; charset=utf-8" +func (c *Context) XML(code int, data string) { + c.W.Header().Set("Content-Type", "application/xml; charset=utf-8") + c.W.WriteHeader(code) + c.W.Write([]byte(data)) +} + +// Error writes an error response to ResponseWriter +// with code and message passed as parameters +// this automatically sets Content-Type to "application/json; charset=utf-8" +// +// Response is a JSON string and contains 3 values: +// error, message, status func (c *Context) Error(code int, msg string) { c.JSON(code, map[string]string{ "error": http.StatusText(code), @@ -28,18 +48,26 @@ func (c *Context) Error(code int, msg string) { }) } +// NotFound is a shortcut to write 404 Error to response writer +// this is based on Error function func (c *Context) NotFound(msg string) { c.Error(http.StatusNotFound, msg) } +// BadRequest is a shortcut to write 400 Error to response writer +// this is based on Error function func (c *Context) BadRequest(msg string) { c.Error(http.StatusBadRequest, msg) } +// Unauthorized is a shortcut to write 401 Error to response writer +// this is based on Error function func (c *Context) Unauthorized(msg string) { c.Error(http.StatusUnauthorized, msg) } +// InternalError is a shortcut to write 500 Error to response writer +// this is based on Error function func (c *Context) InternalError(msg string) { c.Error(http.StatusInternalServerError, msg) } |
