web

package module
v0.0.0-...-11c2234 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 29, 2016 License: MIT Imports: 32 Imported by: 1

README

web.go

web.go is the simplest way to write web applications in the Go programming language. It's ideal for writing simple, performant backend web services.

Features

web.go should be familiar to people who've developed websites with higher-level web frameworks like sinatra or web.py. It is designed to be a lightweight web framework that doesn't impose any scaffolding on the user. Some features include:

  • Routing to url handlers based on regular expressions
  • Secure cookies
  • Support for fastcgi and scgi
  • Web applications are compiled to native code. This means very fast execution and page render speed
  • Efficiently serving static files
  • TLS server support
  • automatic marshaling of JSON and XML content

(A security expert should probably sign off on the TLS support before it becomes a standard.)

Installation

Make sure you have the a working Go environment. See the install instructions.

To install web.go, simply run:

go get github.com/hraban/web

Note that you need to set the environment variable GOPATH before using go get.

Example

    package main

    import (
        "github.com/hraban/web"
    )

    func hello(val string) string {
        return "hello " + val
    } 

    func main() {
        web.Get("/(.*)", hello)
        web.Run("0.0.0.0:9999")
    }

To run the application, put the code in a file called hello.go and run:

go run hello.go

You can point your browser to http://localhost:9999/world .

See http://www.godoc.org/github.com/hraban/web for a tutorial. There are more example applications in the examples directory.

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

Constants

This section is empty.

Variables

View Source
var Config = &mainServer.Config

Configuration of the shared server

Functions

func AddWrapper

func AddWrapper(wrap Wrapper)

func Close

func Close() error

Stop the global web server

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 Get

func Get(route string, handler interface{})

Adds a handler for the 'GET' http method.

func GetHTTPHandler

func GetHTTPHandler() http.Handler

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 Post

func Post(route string, handler interface{})

Adds a handler for the 'POST' http method.

func Put

func Put(route string, handler interface{})

Adds a handler for the 'PUT' http method.

func RegisterMimeEncoder

func RegisterMimeEncoder(mimetype string, enc MimeEncoder)

Register a new mimetype and how it should be encoded

func Run

func Run(addr string) error

Runs the web application and serves http requests

func RunFcgi

func RunFcgi(addr string) error

Runs the web application by serving fastcgi requests

func RunScgi

func RunScgi(addr string) error

Runs the web application and serves scgi requests

func RunTLS

func RunTLS(addr, certFile, keyFile string) error

Runs the secure web application and serves https requests

func SetLogger

func SetLogger(logger *log.Logger)

Set a logger to be used by the global web server

func Urlencode

func Urlencode(data map[string]string) string

URL encode a key/value map to a query string

func Websocket

func Websocket(route string, handler interface{})

Adds a handler for websocket

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) Abort

func (ctx *Context) Abort(status int, body string)

func (*Context) ContentType

func (ctx *Context) ContentType(ext string) string

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) Forbidden

func (ctx *Context) Forbidden(message string)

func (*Context) GetSecureCookie

func (ctx *Context) GetSecureCookie(name string) (string, bool)

func (*Context) Header

func (ctx *Context) Header() http.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 (ctx *Context) NotAcceptable(message string)

func (*Context) NotFound

func (ctx *Context) NotFound(message string)

func (*Context) NotModified

func (ctx *Context) NotModified()

func (*Context) Redirect

func (ctx *Context) Redirect(status int, url_ string)

func (*Context) SetCookie

func (ctx *Context) SetCookie(name, value string, age int64)

Duration is the cookie time-to-live in seconds (0 = forever).

func (*Context) SetSecureCookie

func (ctx *Context) SetSecureCookie(name, val string, age int64)

func (*Context) Unauthorized

func (ctx *Context) Unauthorized(message string)

func (*Context) Write

func (ctx *Context) Write(data []byte) (int, error)

write raw data back to the client

func (*Context) WriteHeader

func (ctx *Context) WriteHeader(status int)

type Encoder

type Encoder interface {
	Encode(data interface{}) error
}

Encode arbitrary data to a response

type MimeEncoder

type MimeEncoder func(w io.Writer) Encoder

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 Params map[string]string

func (Params) GetInt

func (p Params) GetInt(key string) int

Get a parameter as an integer value. Panics if not found or not a legal integer. Panic object is a WebError with status 400.

func (Params) GetString

func (p Params) GetString(key string) string

Get a parameter. Panics if not found. Panic object is a WebError with status 400.

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) Write

func (w *ResponseWriter) Write(data []byte) (int, error)

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 NewServer

func NewServer() *Server

func (*Server) AddWrapper

func (s *Server) AddWrapper(wrap Wrapper)

Queue response wrapper that is called after all other wrappers

func (*Server) Close

func (s *Server) Close() error

Stops the web server

func (*Server) Delete

func (s *Server) Delete(route string, handler interface{})

Adds a handler for the 'DELETE' http method.

func (*Server) Get

func (s *Server) Get(route string, handler interface{})

Adds a handler for the 'GET' http method.

func (*Server) Options

func (s *Server) Options(route string, handler interface{})

Adds a handler for the 'OPTIONS' http method.

func (*Server) Post

func (s *Server) Post(route string, handler interface{})

Adds a handler for the 'POST' http method.

func (*Server) Put

func (s *Server) Put(route string, handler interface{})

Adds a handler for the 'PUT' http method.

func (*Server) Run

func (s *Server) Run(addr string) error

Listen for HTTP connections

func (*Server) RunFcgi

func (s *Server) RunFcgi(addr string) error

Runs the web application and serves fcgi requests for this Server object.

func (*Server) RunScgi

func (s *Server) RunScgi(addr string) error

func (*Server) RunTLS

func (s *Server) RunTLS(addr, certFile, keyFile string) error

Listen for HTTPS connections

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request)

Fully clothed request handler

func (*Server) SetLogger

func (s *Server) SetLogger(logger *log.Logger)

func (*Server) Websocket

func (s *Server) Websocket(route string, handler interface{})

Adds a handler for websocket

type ServerConfig

type ServerConfig struct {
	StaticDirs   []string
	Addr         string
	Port         int
	CookieSecret string
	RecoverPanic bool
	Cert         string
	Key          string
	ColorOutput  bool
}

type SimpleHandler

type SimpleHandler func(*Context) error

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 WebError

type WebError struct {
	Code int
	Err  string
}

func (WebError) Error

func (err WebError) Error() string

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.

Directories

Path Synopsis
Sample applications in web.go Sample web.go application that stores user data in a secure cookie
Sample applications in web.go Sample web.go application that stores user data in a secure cookie

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL