Files
hamlogger/internal/router/context.go
Олег Бородин ada2a49a64 initial import of sources
2024-06-18 10:15:22 +02:00

81 lines
1.7 KiB
Go

package router
import (
"encoding/json"
"fmt"
"net/http"
)
type Context struct {
Req *http.Request
Writer http.ResponseWriter
PathMap map[string]string
StatusCode int
}
func (ctx *Context) SendJSON(payload any) {
ctx.Writer.Header().Set("Content-Type", "application/json")
json.NewEncoder(ctx.Writer).Encode(payload)
}
func (ctx *Context) SendText(payload string) {
ctx.Writer.Header().Set("Content-Type", "text/plain")
ctx.Writer.Write([]byte(payload))
}
func (ctx *Context) SetStatus(httpStatus int) {
ctx.StatusCode = httpStatus
ctx.Writer.WriteHeader(httpStatus)
}
func (ctx *Context) SetHeader(key, value string) {
ctx.Writer.Header().Set(key, value)
}
func (ctx *Context) SendError(httpStatus int) {
ctx.StatusCode = httpStatus
ctx.Writer.WriteHeader(httpStatus)
ctx.Writer.Header().Set("Content-Type", "text/plain")
message := fmt.Sprintf("%d %s", httpStatus, http.StatusText(httpStatus))
ctx.Writer.Write([]byte(message))
}
func (ctx *Context) GetHeader(key string) string {
return ctx.Req.Header.Get(key)
}
func (ctx *Context) GetMethod() string {
return ctx.Req.Method
}
func (ctx *Context) GetQueryMap() map[string][]string {
res := make(map[string][]string)
for key, val := range ctx.Req.URL.Query() {
res[key] = val
}
return res
}
func (ctx *Context) GetQueryVar(key string) string {
return ctx.Req.URL.Query().Get(key)
}
func (ctx *Context) GetPathVar(key string) string {
return ctx.PathMap[key]
}
func (ctx *Context) BindPath(obj any) error {
return bindObj(obj, ctx.PathMap, "uri")
}
func (ctx *Context) BindQuery(obj any) error {
qMap := make(map[string]string)
for key, val := range ctx.Req.URL.Query() {
if len(val) == 1 {
qMap[key] = val[0]
}
}
return bindObj(obj, qMap, "param")
}