router/context.go

122 lines
3.3 KiB
Go
Raw Permalink Normal View History

2018-08-03 21:29:15 +02:00
package router
import (
2018-11-30 14:48:29 +01:00
"bytes"
2018-08-03 21:29:15 +02:00
"encoding/json"
2018-11-30 14:48:29 +01:00
"io"
2020-04-06 16:41:26 +02:00
"net"
2018-08-03 21:29:15 +02:00
"net/http"
2020-04-06 16:41:26 +02:00
"strings"
2018-08-03 21:29:15 +02:00
"github.com/julienschmidt/httprouter"
)
// Context is passed to handlers and middlewares
type Context struct {
2018-08-19 17:04:29 +02:00
router *Router
2018-08-03 21:29:15 +02:00
Request *http.Request
Response http.ResponseWriter
Param func(string) string
store map[string]interface{}
}
2020-04-09 10:41:23 +02:00
// NewContext creates a new context, this function is only exported for use in tests
func NewContext(router *Router, res http.ResponseWriter, req *http.Request, param httprouter.Params) *Context {
2018-08-19 17:04:29 +02:00
return &Context{router, req, res, param.ByName, make(map[string]interface{})}
2018-08-03 21:29:15 +02:00
}
2018-11-30 14:48:07 +01:00
// QueryParam returns the specified parameter from the query string.
// Returns an empty string if it doesn't exist. Returns the first parameter if multiple instances exist
2018-11-30 14:27:00 +01:00
func (c *Context) QueryParam(param string) string {
params := c.Request.URL.Query()[param]
if params == nil {
return ``
}
return params[0]
}
2018-11-30 14:48:07 +01:00
// Redirect sends a redirect to the client
2018-11-30 14:24:28 +01:00
func (c *Context) Redirect(code int, url string) error {
http.Redirect(c.Response, c.Request, url, code)
return nil
}
2018-11-30 14:48:07 +01:00
// Bytes returns the given status code and writes the bytes to the body
2018-08-03 21:29:15 +02:00
func (c *Context) Bytes(code int, b []byte) error {
c.Response.WriteHeader(code)
_, err := c.Response.Write(b)
return err
}
// String returns the given status code and writes the string to the body
func (c *Context) String(code int, s string) error {
c.Response.Header().Set(`Content-Type`, `text/plain`)
2018-08-03 21:29:15 +02:00
c.Response.WriteHeader(code)
_, err := c.Response.Write([]byte(s))
return err
}
// StatusText returns the given status code with the matching status text
func (c *Context) StatusText(code int) error {
return c.String(code, http.StatusText(code))
}
2018-08-03 21:29:15 +02:00
// NoContent returns the given status code without writing anything to the body
func (c *Context) NoContent(code int) error {
c.Response.WriteHeader(code)
return nil
}
// JSON returns the given status code and writes JSON to the body
func (c *Context) JSON(code int, data interface{}) error {
c.Response.Header().Set(`Content-Type`, `application/json`)
2018-08-03 21:29:15 +02:00
c.Response.WriteHeader(code)
return json.NewEncoder(c.Response).Encode(data) // TODO: Encode to buffer first to prevent partial responses on error
}
2018-11-30 14:48:07 +01:00
// Render renders a templating using the Renderer set in router
2018-08-19 17:04:29 +02:00
func (c *Context) Render(code int, template string, data interface{}) error {
if c.router.Renderer == nil {
panic(`Cannot call render without a renderer set`)
}
2018-11-30 14:48:29 +01:00
var b bytes.Buffer
err := c.router.Renderer.Render(&b, template, data, c)
if err != nil {
return err
}
c.Response.Header().Set(`Content-Type`, `text/html`)
2018-08-19 17:04:29 +02:00
c.Response.WriteHeader(code)
2018-11-30 14:48:29 +01:00
_, _ = io.Copy(c.Response, &b)
return nil
2018-08-19 17:04:29 +02:00
}
2018-08-03 21:29:15 +02:00
// Set sets a value in the context. Set is not safe to be used concurrently
func (c *Context) Set(key string, value interface{}) {
c.store[key] = value
}
// Get retrieves a value from the context.
func (c *Context) Get(key string) interface{} {
return c.store[key]
}
2020-04-06 16:41:26 +02:00
// RealIP uses proxy headers for the real ip, if none exist the IP of the current connection is returned
func (c *Context) RealIP() string {
reqIP := c.Request.RemoteAddr
2020-04-06 16:41:26 +02:00
if ip := c.Request.Header.Get(`X-Forwarded-For`); ip != `` {
reqIP = strings.Split(ip, `, `)[0]
} else if ip := c.Request.Header.Get(`X-Real-IP`); ip != `` {
reqIP = ip
2020-04-06 16:41:26 +02:00
}
ra, _, _ := net.SplitHostPort(reqIP)
if ra != `` {
reqIP = ra
2020-04-06 16:41:26 +02:00
}
return reqIP
2020-04-06 16:41:26 +02:00
}