Documentation ¶
Overview ¶
pong is a simple HTTP router for go.
Example:
package main import ( "github.com/gwuhaolin/pong" "net/http" "log" ) func main() { po := pong.New() // visitor http://127.0.0.1:3000/ping will see string "pong" po.Root.Get("/ping", func(c *pong.Context) { c.Response.String("pong") }) // a sub router sub := po.Root.Router("/sub") // visitor http://127.0.0.1:3000/sub/pong will see JSON "{"name":"pong"}" sub.Get("/:name", func(c *pong.Context) { m := map[string]string{ "name":c.Request.Param("name"), } c.Response.JSON(m) }) // Run Server Listen on 127.0.0.1:3000 log.Println(http.ListenAndServe(":3000", po)) }
Learn more at https://github.com/gwuhaolin/pong
Index ¶
- Variables
- type Context
- type HandleFunc
- type Pong
- type Request
- func (req *Request) AutoBind(pointer interface{}) error
- func (req *Request) BindForm(pointer interface{}) error
- func (req *Request) BindJSON(pointer interface{}) error
- func (req *Request) BindQuery(pointer interface{}) error
- func (req *Request) BindXML(pointer interface{}) error
- func (req *Request) File(name string) (multipart.File, *multipart.FileHeader, error)
- func (req *Request) Form(name string) string
- func (req *Request) Param(name string) string
- func (req *Request) Query(name string) string
- type Response
- func (res *Response) Cookie(cookie *http.Cookie)
- func (res *Response) File(filePath string)
- func (res *Response) HTML(html string)
- func (res *Response) Header(name string, value string)
- func (res *Response) JSON(data interface{})
- func (res *Response) JSONP(data interface{}, callback string)
- func (res *Response) Redirect(url string)
- func (res *Response) Render(template string, data interface{})
- func (res *Response) String(str string)
- func (res *Response) XML(data interface{})
- type Router
- func (r *Router) Any(path string, handle HandleFunc)
- func (r *Router) Delete(path string, handle HandleFunc)
- func (r *Router) Get(path string, handle HandleFunc)
- func (r *Router) Head(path string, handle HandleFunc)
- func (r *Router) Middleware(handles ...HandleFunc)
- func (r *Router) Options(path string, handle HandleFunc)
- func (r *Router) Patch(path string, handle HandleFunc)
- func (r *Router) Post(path string, handle HandleFunc)
- func (r *Router) Put(path string, handle HandleFunc)
- func (r *Router) Router(path string) *Router
- func (r *Router) Trace(path string, handle HandleFunc)
- type Session
- type SessionIO
Constants ¶
This section is empty.
Variables ¶
var ( // SessionId's Cookies name store in browser SessionCookiesName = "SESSIONID" // this error will be return when use bind in request when bind data to struct fail ErrorTypeNotSupport = errors.New("type not support") )
Functions ¶
This section is empty.
Types ¶
type Context ¶
type Context struct { // HTTP Session Session *Session // HTTP Request,used to get params like query post-form post-file... Request *Request // HTTP Response,used to send response to client.Can send JSON XML string file... Response *Response // contains filtered or unexported fields }
Context represents context for the current request. It holds request and response objects, path parameters, data and registered handler. Context is handle by middleware list in order
func (*Context) DestorySession ¶
remove sessionId this will remove sessionId store in browser's cookie and session manager's store
func (*Context) Get ¶
get a value which is set by Context.Set() method. if the give name is not store a nil will return
func (*Context) ResetSession ¶
update old sessionId with new one this will update sessionId store in browser's cookie and session manager's store
type HandleFunc ¶
type HandleFunc func(*Context)
HandleFunc is a handle in Middleware list, like a machine production line to do some change used to read something from request and store by Context.Request make a response to client by Context.Response
type Pong ¶
type Pong struct { // Root router to path / Root *Router // 404 not find handle // when pong's router can't find a handle to request' URL,pong will use NotFindHandle to handle this request // default is response with code 404, and string page not find NotFindHandle HandleFunc // when send response to client cause error happen, pong will use HTTPErrorHandle to handle this request // default is response with code 500, and string inter server error HTTPErrorHandle func(error, *Context) // contains filtered or unexported fields }
func (*Pong) EnableSession ¶
if you want you HTTP session call this EnableSession will use memory to store session data EnableSession will read sessionId from request cookies value by name SessionCookiesName default is "SESSIONID" as sessionId EnableSession will cause performance drop compare to not use Session
func (*Pong) LoadTemplateGlob ¶
load HTML template files whit glob if you will use render in response,you must call LoadTemplateGlob first to load template files. LoadTemplateGlob creates a new Template and parses the template definitions from the files identified by the pattern, which must match at least one file. The returned template will have the (base) name and (parsed) contents of the first file matched by the pattern. LoadTemplateGlob is equivalent to calling ParseFiles with the list of files matched by the pattern.
func (*Pong) ServeHTTP ¶
func (pong *Pong) ServeHTTP(writer http.ResponseWriter, request *http.Request)
http.Server's ListenAndServe Handler
func (*Pong) TailMiddleware ¶
func (pong *Pong) TailMiddleware(middlewareList ...HandleFunc)
add a middleware in the process's tail. which will execute before response data to client and after all of the other middleware register in router if you add more than one middlewares,this middlewares will execute in order
type Request ¶
type Request struct { //point to http.Request in golang's standard lib HTTPRequest *http.Request // contains filtered or unexported fields }
A Request represents an HTTP request received by a server or to be sent by a client. Request has some convenient method to get params form client
func (*Request) AutoBind ¶
auto bind will look request's http Header ContentType
if request ContentType is applicationJSON will use BindJSON to parse if request ContentType is applicationXML will use BindXML to parse if request ContentType is applicationForm or multipartForm will use BindForm to parse else will return an ErrorTypeNotSupport error
func (*Request) BindForm ¶
parse request's body post form as map and bind data to struct use filed name
an error will return if the struct filed type is not support
func (*Request) BindJSON ¶
parse request's body data as JSON and use standard lib json.Unmarshal to bind data to struct
an error will return if json.Unmarshal return error
func (*Request) BindQuery ¶
parse request's query params as map and bind data to struct use filed name
an error will return if the struct filed type is not support
func (*Request) BindXML ¶
parse request's body data as XML and use standard lib XML.Unmarshal to bind data to struct
an error will return if xml.Unmarshal return error
func (*Request) Form ¶
get Form param form request's body
returns the first value for the named component of the POST or PUT request body. URL query parameters are ignored. support both application/x-www-form-urlencoded and multipart/form-data
If key is not present, returns the empty string.
type Response ¶
type Response struct { // point to http.ResponseWriter in golang's standard lib HTTPResponseWriter http.ResponseWriter // HTTP status code response to client StatusCode int // contains filtered or unexported fields }
is used by an HTTP handler to response to client's request.
func (*Response) File ¶
send a file response to client
replies to the request with the contents of the named file or directory. If the provided file or direcory name is a relative path, it is interpreted relative to the current directory and may ascend to parent directories. If the provided name is constructed from user input, it should be sanitized before calling ServeFile. As a precaution, ServeFile will reject requests where r.URL.Path contains a ".." path element.
As a special case, ServeFile redirects any request where r.URL.Path ends in "/index.html" to the same path, without the final "index.html". To avoid such redirects either modify the path or use ServeContent.
func (*Response) JSON ¶
func (res *Response) JSON(data interface{})
send JSON response to client
parse data by standard lib's json.Marshal and then send to client
if json.Marshal fail will call HTTPErrorHandle with error and context,to handle error you should define your pong.HTTPErrorHandle
func (*Response) JSONP ¶
send JSONP response to client
parse data by standard lib's json.Marshal and then send to client will wrap json to JavaScript's call method with give callback param
if json.Marshal fail will call HTTPErrorHandle with error and context,to handle error you should define your pong.HTTPErrorHandle
func (*Response) Redirect ¶
Redirect replies to the request with a redirect to url, which may be a path relative to the request path.
The Response.StatusCode should be in the 3xx range and is usually StatusMovedPermanently, StatusFound or StatusSeeOther.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
func (*Router) Any ¶
func (r *Router) Any(path string, handle HandleFunc)
register an path to handle any type HTTP request incloud "GET" "HEAD" "POST" "PUT" "PATCH" "DELETE" "CONNECT" "OPTIONS" "TRACE"
func (*Router) Delete ¶
func (r *Router) Delete(path string, handle HandleFunc)
register an path to handle HTTP Delete request
func (*Router) Get ¶
func (r *Router) Get(path string, handle HandleFunc)
register an path to handle HTTP Get request
func (*Router) Head ¶
func (r *Router) Head(path string, handle HandleFunc)
register an path to handle HTTP Head request
func (*Router) Middleware ¶
func (r *Router) Middleware(handles ...HandleFunc)
add a Middleware to this router this Middleware list will execute in order before execute the handle you provide to response all of this router's sub router will also execute this Middleware list,parent's Middleware list first child's Middleware list later
func (*Router) Options ¶
func (r *Router) Options(path string, handle HandleFunc)
register an path to handle HTTP Options request
func (*Router) Patch ¶
func (r *Router) Patch(path string, handle HandleFunc)
register an path to handle HTTP Patch request
func (*Router) Post ¶
func (r *Router) Post(path string, handle HandleFunc)
register an path to handle HTTP Post request
func (*Router) Put ¶
func (r *Router) Put(path string, handle HandleFunc)
register an path to handle HTTP Put request
func (*Router) Trace ¶
func (r *Router) Trace(path string, handle HandleFunc)
register an path to handle HTTP Trace request
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
type SessionIO ¶
type SessionIO interface { // NewSession should generate a sessionId which is unique compare to existent,and return this sessionId // this sessionId string will store in browser by cookies,so the sessionId string should compatible with cookies value rule NewSession() (sessionId string) // Destory should do operation to remove an session's data in store by give sessionId Destory(sessionId string) error // Reset should update the give old sessionId to a new id,but the value should be the same Reset(oldSessionId string) (newSessionId string, err error) // return whether this sessionId is existent in store Has(sessionId string) bool // read the whole value point to the give sessionId Read(sessionId string) (wholeValue map[string]interface{}) // update the sessionId's value to store // the give value just has changed part not all of the value point to sessionId Write(sessionId string, changes map[string]interface{}) error }
SessionIO define a interface to handle Session's read and write pong provide a in memory session manager as default stand by SessionManager interface you can define yourself's SessionManager like store session to Redis,MongoDB,File