Documentation
¶
Index ¶
- Constants
- Variables
- func ParseParams(c *Context) error
- func Scheme(vals map[string]interface{}, dst interface{}) (err error)
- func SchemeParam(vals map[string]interface{}, dst interface{}, tag string) (err error)
- type Context
- func (c *Context) Scheme(ptrArgs interface{}) error
- func (c *Context) SchemeBool(tag string) (v bool, err error)
- func (c *Context) SchemeInt(tag string) (v int, err error)
- func (c *Context) SchemeInt64(tag string) (v int64, err error)
- func (c *Context) SchemeParam(ptrArg interface{}, tag string) error
- func (c *Context) SchemeString(tag string) (v string, err error)
- type DefaultResponser
- type Error
- type Handler
- type Logger
- type Middleware
- type MiddlewaresManager
- type ResponseMiddleware
- type Responser
- type Result
- type Router
- type StatusCode
- type StdLogger
- type Web
- func (w *Web) Append(midd Middleware)
- func (w *Web) Close()
- func (w *Web) Handle(method string, path string, fn Handler) *MiddlewaresManager
- func (w *Web) Listen(protocol string, addr string) error
- func (w *Web) ListenAndServe(protocol string, addr string) error
- func (w *Web) Serve() error
- func (w *Web) ServeHTTP(rw http.ResponseWriter, req *http.Request)
- func (w *Web) SetLogger(l Logger)
- func (w *Web) SetResponser(r Responser)
- func (w *Web) SubRouter(pathPerfix string) Router
- type Writeable
Constants ¶
const ( StatusOK = http.StatusOK // 200 StatusBadRequest = http.StatusBadRequest // 400 StatusForbidden = http.StatusForbidden // 403 StatusNotFound = http.StatusNotFound // 404 StatusInternalServerError = http.StatusInternalServerError // 500 )
const ( POST = "POST" GET = "GET" DELETE = "DELETE" PUT = "PUT" OPTIONS = "OPTIONS" )
Variables ¶
var HttpReadTimeout = time.Minute
var MaxBodyLength int64 = 20 * (1 << 20) // 20M
var ResultOK = Result{"result": "ok"}
var SchemeTagName = "web"
Tag name for Scheme.
Functions ¶
func ParseParams ¶
func SchemeParam ¶
Types ¶
type Context ¶
type Context struct { Request *http.Request RequestId int64 ResponseWriter http.ResponseWriter ResponseHeader http.Header Values map[string]interface{} RawPostData []byte Multipart []*struct { FormName string FileName string Header textproto.MIMEHeader Data []byte } }
func (*Context) SchemeParam ¶
type DefaultResponser ¶
type DefaultResponser struct { }
func (*DefaultResponser) Response ¶
func (r *DefaultResponser) Response(w http.ResponseWriter, result interface{}) (int, error)
type Error ¶
type Error struct { Err string `json:"error"` Message string `json:"message,omitempty"` Code int `json:"-"` }
func NewErrorMsg ¶
func (*Error) StatusCode ¶
type Middleware ¶
type MiddlewaresManager ¶
type MiddlewaresManager struct {
// contains filtered or unexported fields
}
func (*MiddlewaresManager) Append ¶
func (m *MiddlewaresManager) Append(midd Middleware) *MiddlewaresManager
type ResponseMiddleware ¶
type Responser ¶
type Responser interface {
Response(w http.ResponseWriter, result interface{}) (code int, err error)
}
type Result ¶
type Result map[string]interface{}
func (Result) SetStatusCode ¶
func (Result) StatusCode ¶
type Router ¶
type Router interface { // Register the Handler to handle this url. Method can be http methods like "GET", "POST", // "DELETE" etc, case insensitive. The path is related to the base path of this router. // All middlewares already in this router will be applied to this handler. But new // middlewares after will not affect. It will panic if you handle two functions with // the same url. Handle(method string, path string, fn Handler) *MiddlewaresManager // Append a middleware to this router. Middlewares will applied to handler in sequence. Append(midd Middleware) // Get a sub router with add this path. Note that the base path of sub router // is based on current base path. Middlewares in the sub router is a copy of // this router. But after this, they will be independent with each other. SubRouter(path string) Router }
A router to handle url and to manage middlewares. Web is a router based on the root path.
Example:
w := web.NewWeb() // w based on / r1 := w.SubRouter("/api") // r1 based on /api r2 := r1.SubRouter("message") // r2 based on /api/message r2.Append(NewAuthMiddleware()) // r2 add AuthMiddleware r3 := r2.SubRouter("/") // r3 based on /api/message, with AuthMiddleware. The same as r2. r2.Append(NewRateLimitMiddleware()) // r2 add RateLimitMiddleware r1.Handle("GET", "/status", Status) // GET /api/status, without Middleware r2.Handle("POST", "/add", AddMessage) // POST /api/message/add, with AuthMiddleware and RateLimitMiddleware r3.Handle("DELETE", "/del", DelMessage) // DELETE /api/message/del, with AuthMiddleware
type StatusCode ¶
type StatusCode interface {
StatusCode() int
}
type Web ¶
type Web struct {
// contains filtered or unexported fields
}
Web is the main object of the framework. All things start from here. To create an Web object, call NewWeb().
You can use this web framework to handle HTTP requests by writing your own functions and return results with JSON format (or other custom format if you want).
Note that this framework is designed for API server. To keep it simple, it doesn't support static page, html template, css, javascript etc.
Here is an example:
import "github.com/tiaotiao/web" func Hello(c *web.Context) interface{} { return "hello world" // return a string will be write directly with out processing. } func Echo(c *web.Context) interface{} { args := struct { Message string `web:"message,required"` }{} // scheme args from c.Values into args by the indication of struct tags. if err := web.Scheme(c.Values, &args); err != nil { return err // error occured if lack of argument or wrong type. } return web.Result{"message": args.Message} // a map or struct will be formated to JSON } func main() { w := web.NewWeb() w.Handle("GET", "/api/hello", Hello) w.Handle("GET", "/api/echo", Echo) w.ListenAndServe("tcp", ":8082") // block forever until be closed }
func (*Web) Handle ¶
func (w *Web) Handle(method string, path string, fn Handler) *MiddlewaresManager
Register an Handler as a handler for this url. See Router.Handle
func (*Web) Listen ¶
Listen on the local network address. Argument protocol usually be 'tcp' or 'unix'. Argument addr usually be the format as 'host:port'. For example:
Listen("tcp", ":8080") // listen on 8080 port Listen("tcp", "google.com:http") // listen on 80 port from google.com Listen("unix", "/var/run/web_server.sock")
See net.Listen for more.
func (*Web) ListenAndServe ¶
Listen an address and start to serve. Blocked until be closed or some error occurs. See Web.Listen and Web.Serve.
func (*Web) ServeHTTP ¶
func (w *Web) ServeHTTP(rw http.ResponseWriter, req *http.Request)
ServeHTTP used for implements http.Handler interface. No need to be called by user.
func (*Web) SetResponser ¶
To setup a custom responser to process the result which returned from Handler and then to write into response body. The responser must implements the Responser interface.
With out doing anything, the DefaultResponser will write string and []byte directly or write map, struct and other types in JSON format. See DefaultResponser for more detail.
type Writeable ¶
type Writeable interface {
OnWrite(w http.ResponseWriter) error
}