Files
go-tower/context.go

118 lines
2.5 KiB
Go

package tower
import (
"context"
"encoding/json"
"encoding/xml"
"net/http"
"github.com/julienschmidt/httprouter"
)
type Context struct {
request *http.Request
response *responseWriter
params httprouter.Params
}
type ContextKey string
func (c *Context) Request() *http.Request {
return c.request
}
func (c *Context) Response() http.ResponseWriter {
return c.response
}
func (c *Context) Query(key string) string {
return c.request.URL.Query().Get(key)
}
func (c *Context) Param(key string) string {
return c.params.ByName(key)
}
func (c *Context) Value(key ContextKey) any {
return c.request.Context().Value(key)
}
func (c *Context) SetValue(key ContextKey, value any) {
ctx := context.WithValue(c.request.Context(), key, value)
c.request = c.request.WithContext(ctx)
}
func (c *Context) Cookie(key string) (*http.Cookie, error) {
return c.request.Cookie(key)
}
func (c *Context) SetCookie(cookie *http.Cookie) {
http.SetCookie(c.response, cookie)
}
func (c *Context) Header(key string) string {
return c.request.Header.Get(key)
}
func (c *Context) SetHeader(key, value string) {
c.response.Header().Set(key, value)
}
func (c *Context) Status() int {
return c.response.Status()
}
func (c *Context) SetStatus(code int) {
c.response.WriteHeader(code)
}
func (c *Context) ClientIP() string {
if ip := c.Header("X-Forwarded-For"); ip != "" {
return ip
}
if ip := c.Header("X-Real-IP"); ip != "" {
return ip
}
return c.request.RemoteAddr
}
func (c *Context) Redirect(code int, url string) {
http.Redirect(c.response, c.request, url, code)
}
func (c *Context) WriteBytes(code int, b []byte, contentType string) error {
c.SetStatus(code)
c.SetHeader("Content-Type", contentType)
_, err := c.response.Write(b)
return err
}
func (c *Context) WriteString(code int, v string) error {
c.SetStatus(code)
c.SetHeader("Content-Type", "text/plain; charset=utf-8")
_, err := c.response.Write([]byte(v))
return err
}
func (c *Context) WriteJSON(code int, v any) error {
c.SetStatus(code)
c.SetHeader("Content-Type", "application/json; charset=utf-8")
return json.NewEncoder(c.response).Encode(v)
}
func (c *Context) WriteXML(code int, v any) error {
c.SetStatus(code)
c.SetHeader("Content-Type", "application/xml; charset=utf-8")
return xml.NewEncoder(c.response).Encode(v)
}
func (c *Context) BindJSON(v any) error {
return json.NewDecoder(c.request.Body).Decode(v)
}
func (c *Context) BindXML(v any) error {
return xml.NewDecoder(c.request.Body).Decode(v)
}