103 lines
2 KiB
Go
103 lines
2 KiB
Go
package server
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/gorilla/mux"
|
|
)
|
|
|
|
func newContext(w http.ResponseWriter, r *http.Request, srv *Server) *Context {
|
|
h := w.Header()
|
|
h.Set("Content-Type", "application/json")
|
|
return &Context{
|
|
Status: http.StatusOK,
|
|
Request: r,
|
|
Response: w,
|
|
s: srv,
|
|
}
|
|
}
|
|
|
|
// Context is the context object shared between http handlers
|
|
type Context struct {
|
|
Body []byte
|
|
Status int
|
|
|
|
Request *http.Request
|
|
Response http.ResponseWriter
|
|
s *Server
|
|
}
|
|
|
|
// Method returns the request method
|
|
func (c *Context) Method() string {
|
|
return c.Request.Method
|
|
}
|
|
|
|
// GetHeader returns the given http header
|
|
func (c *Context) GetHeader(name string) string {
|
|
return c.Request.Header.Get(name)
|
|
}
|
|
|
|
// SetHeader sets the given http header
|
|
func (c *Context) SetHeader(name, value string) {
|
|
h := c.Response.Header()
|
|
h.Set(name, value)
|
|
}
|
|
|
|
// Form returns the given form value
|
|
func (c *Context) Form(name string) string {
|
|
return c.Request.FormValue(name)
|
|
}
|
|
|
|
// Var returns the given url variable
|
|
func (c *Context) Var(name string) (ret string) {
|
|
ret, _ = mux.Vars(c.Request)[name]
|
|
return
|
|
}
|
|
|
|
func (c *Context) log() {
|
|
c.s.log.Info("access",
|
|
"addr", c.Request.RemoteAddr,
|
|
"method", c.Request.Method,
|
|
"url", c.Request.URL,
|
|
"status", c.Status,
|
|
)
|
|
}
|
|
|
|
func (c *Context) NotFound() {
|
|
c.Status = http.StatusNotFound
|
|
c.Response.WriteHeader(http.StatusNotFound)
|
|
c.Response.Write([]byte(`{"message":"not found","status":404}`))
|
|
c.log()
|
|
}
|
|
|
|
// OK is a empty HTTP 200 JSON response
|
|
func (c *Context) OK() {
|
|
c.Response.Write([]byte("{}"))
|
|
c.log()
|
|
}
|
|
|
|
// JSON is a json response
|
|
func (c *Context) JSON(v interface{}) {
|
|
err := json.NewEncoder(c.Response).Encode(v)
|
|
if err != nil {
|
|
c.Err(ise)
|
|
return
|
|
}
|
|
c.log()
|
|
}
|
|
|
|
// Err is a HTTPErr wrapper for the custom Error type
|
|
func (c *Context) Err(err Error) {
|
|
c.HTTPErr(err.Error(), err.Status())
|
|
}
|
|
|
|
// HTTPErr is a http.Error wrapper
|
|
func (c *Context) HTTPErr(err string, status int) {
|
|
c.Status = status
|
|
http.Error(c.Response, err, status)
|
|
c.log()
|
|
}
|
|
|
|
type ctxHandler func(*Context)
|