Files
mstore/app/router/context.go
T
2026-02-06 09:27:45 +02:00

76 lines
1.7 KiB
Go

package router
import (
"context"
"encoding/json"
"net/http"
)
type Context struct {
Ctx context.Context
Request *http.Request
Writer http.ResponseWriter
PathMap map[string]string
StatusCode int
}
func NewContext(writer http.ResponseWriter, request *http.Request) *Context {
ctx := context.Background()
rctx := &Context{
Writer: writer,
Request: request,
Ctx: ctx,
PathMap: make(map[string]string),
}
return rctx
}
// Request
func (rctx *Context) GetSubpath(key string) (string, bool) {
value, exists := rctx.PathMap[key]
return value, exists
}
func (rctx *Context) GetQuery(key string) string {
return rctx.Request.URL.Query().Get(key)
}
func (rctx *Context) GetHeader(key string) string {
return rctx.Request.Header.Get(key)
}
func (rctx *Context) GetHeaders() http.Header {
return rctx.Request.Header
}
func (rctx *Context) GetContext() context.Context {
return rctx.Request.Context()
}
// Response
func (rctx *Context) SetHeader(key, value string) {
rctx.Writer.Header().Set(key, value)
}
func (rctx *Context) SetStatus(httpStatus int) {
rctx.StatusCode = httpStatus
rctx.Writer.WriteHeader(httpStatus)
}
func (rctx *Context) SendJSON(statusCode int, payload any) {
rctx.Writer.Header().Set("Content-Type", "application/json")
rctx.Writer.WriteHeader(statusCode)
json.NewEncoder(rctx.Writer).Encode(payload)
}
func (rctx *Context) SendText(statusCode int, payload string) {
rctx.Writer.Header().Set("Content-Type", "text/plain")
rctx.Writer.WriteHeader(statusCode)
rctx.Writer.Write([]byte(payload))
}
func (rctx *Context) SendBytes(statusCode int, payload []byte) {
rctx.Writer.WriteHeader(statusCode)
rctx.Writer.Write(payload)
}