Documentation ¶
Overview ¶
Simple web framework.
At the core of web.go are request handlers:
func helloworld() string { return "hello, world" }
These are hooked up to the routing table using web.go:
func main() { web.Get("/", helloworld) web.Run("127.0.0.1:9999") }
Now visit http://127.0.0.1:9999 to see the greeting
The routing table is based on regular expressions and allows parameter groups:
func hello(name string) string { return "hello, " + name } func main() { web.Get("/(.*)", hello) web.Run("127.0.0.1:9999") }
Visit http://127.0.0.1:9999/fidodido to see 'hello, fidodido'
Route handlers may contain a pointer to web.Context as their first parameter. This variable serves many purposes -- it contains information about the request, and it provides methods to control the http connection.
See the examples directory for more examples.
Index ¶
- Variables
- func AddWrapper(wrap Wrapper)
- func Close() error
- func CompressWrapper(h SimpleHandler, ctx *Context) error
- func Delete(route string, handler interface{})
- func Get(route string, handler interface{})
- func GetHTTPHandler() http.Handler
- func GuessMimetypeWrapper(h SimpleHandler, ctx *Context) error
- func Options(route string, handler interface{})
- func Post(route string, handler interface{})
- func Put(route string, handler interface{})
- func RegisterMimeEncoder(mimetype string, enc MimeEncoder)
- func Run(addr string) error
- func RunFcgi(addr string) error
- func RunScgi(addr string) error
- func RunTLS(addr, certFile, keyFile string) error
- func SetLogger(logger *log.Logger)
- func Urlencode(data map[string]string) string
- func Websocket(route string, handler interface{})
- type AccessLogger
- type Context
- func (ctx *Context) Abort(status int, body string)
- func (ctx *Context) ContentType(ext string) string
- func (ctx *Context) Forbidden(message string)
- func (ctx *Context) GetSecureCookie(name string) (string, bool)
- func (ctx *Context) Header() http.Header
- func (ctx *Context) NotAcceptable(message string)
- func (ctx *Context) NotFound(message string)
- func (ctx *Context) NotModified()
- func (ctx *Context) Redirect(status int, url_ string)
- func (ctx *Context) SetCookie(name, value string, age int64)
- func (ctx *Context) SetSecureCookie(name, val string, age int64)
- func (ctx *Context) Unauthorized(message string)
- func (ctx *Context) Write(data []byte) (int, error)
- func (ctx *Context) WriteHeader(status int)
- type Encoder
- type MimeEncoder
- type OneAccessLogger
- type Params
- type ResponseWriter
- func (w *ResponseWriter) AddAfterHeaderFunc(f func(*ResponseWriter))
- func (w *ResponseWriter) Close() error
- func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (w *ResponseWriter) Success() bool
- func (w *ResponseWriter) WrapBodyWriter(f func(w io.Writer) io.Writer)
- func (w *ResponseWriter) Write(data []byte) (int, error)
- func (w *ResponseWriter) WriteHeader(status int)
- type Server
- func (s *Server) AddWrapper(wrap Wrapper)
- func (s *Server) Close() error
- func (s *Server) Delete(route string, handler interface{})
- func (s *Server) Get(route string, handler interface{})
- func (s *Server) Options(route string, handler interface{})
- func (s *Server) Post(route string, handler interface{})
- func (s *Server) Put(route string, handler interface{})
- func (s *Server) Run(addr string) error
- func (s *Server) RunFcgi(addr string) error
- func (s *Server) RunScgi(addr string) error
- func (s *Server) RunTLS(addr, certFile, keyFile string) error
- func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (s *Server) SetLogger(logger *log.Logger)
- func (s *Server) Websocket(route string, handler interface{})
- type ServerConfig
- type SimpleHandler
- type WebError
- type Wrapper
Constants ¶
This section is empty.
Variables ¶
var Config = &mainServer.Config
Configuration of the shared server
Functions ¶
func AddWrapper ¶
func AddWrapper(wrap Wrapper)
func CompressWrapper ¶
func CompressWrapper(h SimpleHandler, ctx *Context) error
Compress response data when applicable (client wants it and response is suitable)
func Delete ¶
func Delete(route string, handler interface{})
Adds a handler for the 'DELETE' http method.
func GetHTTPHandler ¶
The global web server as an object implementing the http.Handler interface
func GuessMimetypeWrapper ¶
func GuessMimetypeWrapper(h SimpleHandler, ctx *Context) error
Guess the mime type of the response based on the request path if not explicitly set by the handler
func Options ¶
func Options(route string, handler interface{})
Adds a handler for the 'OPTIONS' http method.
func RegisterMimeEncoder ¶
func RegisterMimeEncoder(mimetype string, enc MimeEncoder)
Register a new mimetype and how it should be encoded
Types ¶
type AccessLogger ¶
type AccessLogger func(*Server) OneAccessLogger
Factory function that generates new one-shot access loggers
type Context ¶
type Context struct { // The incoming request that led to this handler being invoked Request *http.Request RawBody []byte // Aggregated parameters from the query string and POST data. Params Params Server *Server // Copied from Server.User before the handler is invoked. Use this to // communicate global state between your handlers. User interface{} // The response writer that the handler should write to. Response *ResponseWriter // In the case of websocket: a reference to the connection object. Nil // otherwise. WebsockConn *websocket.Conn // contains filtered or unexported fields }
Custom web.go request context. Contains information about the request and can be used to manipulate the response.
func (*Context) ContentType ¶
Sets the content type by extension, as defined in the mime package. For example, ctx.ContentType("json") sets the content-type to "application/json" if the supplied extension contains a slash (/) it is set as the content-type verbatim without passing it to mime. returns the content type as it was set, or an empty string if none was found.
func (*Context) Header ¶
Response headers not request headers. For clarity use Context.Response.Header() this method exists so Context satisfies the http.ResponseWriter interface.
func (*Context) NotAcceptable ¶
func (*Context) NotModified ¶
func (ctx *Context) NotModified()
func (*Context) SetSecureCookie ¶
func (*Context) Unauthorized ¶
func (*Context) WriteHeader ¶
type Encoder ¶
type Encoder interface {
Encode(data interface{}) error
}
Encode arbitrary data to a response
type MimeEncoder ¶
type OneAccessLogger ¶
type OneAccessLogger interface { // Called with the raw incoming request LogRequest(*http.Request) // Parameters as parsed by web.go LogParams(Params) // Called when headers are set by handler and will be written to client LogHeader(status int, header http.Header) // Called when response has been written to client. If an error occurred at // any point during handling it is passed as an argument. Otherwise err is // nil. LogDone(err error) }
Log one request by calling every method in the order defined below. Logging may be done in a separate goroutine from handling. Arguments are passed by reference for efficiency but MUST NOT be changed!
func DefaultAccessLogger ¶
func DefaultAccessLogger(s *Server) OneAccessLogger
Simple stateless access logger that prints all requests to server.Logger
type Params ¶
type ResponseWriter ¶
type ResponseWriter struct { // Underlying response writer, only use this for the headers http.ResponseWriter // body data is written here. can be wrapped by afterheaders functions BodyWriter io.Writer // contains filtered or unexported fields }
wrap http.ResponseWriter to allow function hooks that are executed after the response headers are set and after the body is sent.
func (*ResponseWriter) AddAfterHeaderFunc ¶
func (w *ResponseWriter) AddAfterHeaderFunc(f func(*ResponseWriter))
Add callback to execute when all headers have been set and body data is about to be written
func (*ResponseWriter) Close ¶
func (w *ResponseWriter) Close() error
func (*ResponseWriter) Hijack ¶
func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
func (*ResponseWriter) Success ¶
func (w *ResponseWriter) Success() bool
True if the writer has sent a status code to the client indicating success
func (*ResponseWriter) WrapBodyWriter ¶
func (w *ResponseWriter) WrapBodyWriter(f func(w io.Writer) io.Writer)
func (*ResponseWriter) WriteHeader ¶
func (w *ResponseWriter) WriteHeader(status int)
type Server ¶
type Server struct { Config ServerConfig // All error / info logging is done to this logger Logger *log.Logger // Passed verbatim to every handler on every request User interface{} // All requests are passed through this wrapper if defined Wrappers []Wrapper // Factory function that generates access loggers, only used to log requests AccessLogger AccessLogger // contains filtered or unexported fields }
func (*Server) AddWrapper ¶
Queue response wrapper that is called after all other wrappers
type ServerConfig ¶
type SimpleHandler ¶
internal generic handler type. parameters, if any, have been closed. also represents non-user defined handlers like ServeFile and wrapped handlers. Call this with a context and it will perform all necessary magic and finally write the response to the client. Only exported to allow external definition of wrappers.
type Wrapper ¶
type Wrapper func(SimpleHandler, *Context) error
Called for every request and passed the handler that web.go thinks should be called to process this specific request. Use this to do some global tinkering like:
* specialized error pages (if werr, ok := err.(WebError); ok { ... })
* encode data if client supports it (gzip etc)
* set site-wide headers
Note that when a wrapper is called by web.go the actual handler itself is NOT called by web.go it must be called by the wrapper. This allows fine-grained control over the context in which to call it and what to do with potential errors.
The handler does not have to be a user-defined handler object: web.go creates handlers on the fly to handle static files, 404 situations and handler signature mismatches. It is whatever web.go WOULD have called if a wrapper were not defined.