uweb

package module
v0.0.0-...-d71580b Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2013 License: BSD-3-Clause Imports: 25 Imported by: 0

README

µweb

A micro web framework for Go.

Build Status

Overview

µweb is a small library designed to simplify the creation of web apps in Go.

It is heavily inspired by the Python library BottlePy.

Note: µweb is currently pre-alpha. The existing API is fairly stable but may change.

Example: Hello World

package main

import (
    "github.com/calebbrown/uweb"
    "fmt"
)

func main() {
    uweb.Route("^hello/(.*)$", func(name string) string {
        return fmt.Sprintf("<b>Hello, %s!</b>!", name)
    })
    uweb.Run("localhost:8080")
}

Copy and paste this code into an editor, save the file as hello.go, in a shell run go run hello.go, then point your browser to localhost:8080/hello/world.

Installation

Make sure you have Go 1.1 installed and $GOPATH is set.

go get github.com/calebbrown/uweb

Documentation

Visit http://godoc.org/github.com/calebbrown/uweb or simply run godoc -http=":6060" after installation and visit localhost:6060/pkg/github.com/calebbrown/uweb.

Documentation

Overview

Package μweb is a micro web framework.

It's purpose is to make building complex web apps simple.

µweb is currently pre-alpha. As such there are some features that are currently broken, or not yet implemented.

Index

Examples

Constants

View Source
const (
	BUILD_FILE string = "autoreload.out"
	LOCK_FILE  string = "autoreload.lock"
)

Variables

View Source
var Config struct {
	Debug         bool
	AutoReload    bool
	Logging       bool
	CookieOptions *CookieOptions
}

Configuration for µweb

When Debug is set to true messages will be logged to stdout.

When AutoReload is set to true, and Debug is set to true a call to Run() will wrap the execution up so that when a change is detected on a dependency it will restart the execution of the web application.

Functions

func Abort

func Abort(code int, message string)

Abort breaks out of the current view and returns an error response

func MyView() string {
    r, err := myFunc()
    if err != nil {
        Abort(503, "Oh no, an error occured!")
    }
    return r
}

func AutoReloader

func AutoReloader()

func Delete

func Delete(pattern string, target Target) error

func Error

func Error(code int, handler ErrorHandler)

func Get

func Get(pattern string, target Target) error
func Head(pattern string, target Target) error

func Mount

func Mount(pattern string, handler Handler) error
Example
package main

import (
	"github.com/calebbrown/uweb"
)

func main() {
	app := uweb.NewApp()

	app.Get("^bar/(.*)", func(name string) string {
		return "Hello, " + name
	})

	uweb.Mount("^foo/", app)

	uweb.Run("localhost:6060")
}
Output:

func Options

func Options(pattern string, target Target) error

func Patch

func Patch(pattern string, target Target) error

func Post

func Post(pattern string, target Target) error

func Put

func Put(pattern string, target Target) error

func Redirect

func Redirect(url string)

Redirect breaks out of the current view and returns a redirect (302) response, redirecting the User-Agent to the specified URL

func MyView() {
    Redirect("http://example.com/")
}

func RedirectWithCode

func RedirectWithCode(url string, code int)

RedirectWithCode behaves like Redirect, but allows a custom HTTP status code to be supplied.

The status code must be a valid redirect code (301, 302, 303, 307, 308)

func Route

func Route(pattern string, target Target) error

func Run

func Run(host string) error

func RunFcgi

func RunFcgi(host string) error

func Serve

func Serve(l net.Listener) error

func ServeFcgi

func ServeFcgi(l net.Listener) error

Types

type App

type App struct {
	// contains filtered or unexported fields
}

An App is used to encapsulate a group of related routes.

Example

This example demonstrates a custom instance of App.

package main

import (
	"github.com/calebbrown/uweb"
)

func main() {
	app := uweb.NewApp()

	app.Get("^hello/(.*)", func(name string) string {
		return "Hello, " + name
	})

	app.Post("^submit/$", func(ctx *uweb.Context) {

	})

	app.Run("localhost:6060")
}
Output:

var DefaultApp *App

Default instance of App

func NewApp

func NewApp() *App

Creates a new empty App

func (*App) Delete

func (a *App) Delete(pattern string, target Target) error

Map a function to a url pattern for DELETE requests

func (*App) Error

func (a *App) Error(code int, handler ErrorHandler)

Register a handler to be called when an ErrorResponse is returned

func (*App) Get

func (a *App) Get(pattern string, target Target) error

Map a function to a url pattern for GET requests

func (*App) Handle

func (a *App) Handle(ctx *Context) *Response

func (*App) Head

func (a *App) Head(pattern string, target Target) error

Map a function to a url pattern for HEAD requests

func (*App) Mount

func (a *App) Mount(pattern string, handler Handler) error

Mount an application (uweb.App or anything that implements the Handler interface) at a specific url pattern

func (*App) Options

func (a *App) Options(pattern string, target Target) error

Map a function to a url pattern for OPTIONS requests

func (*App) Patch

func (a *App) Patch(pattern string, target Target) error

Map a function to a url pattern for PATCH requests

func (*App) Post

func (a *App) Post(pattern string, target Target) error

Map a function to a url pattern for POST requests

func (*App) Put

func (a *App) Put(pattern string, target Target) error

Map a function to a url pattern for PUT requests

func (*App) Reset

func (a *App) Reset()

Resets the App back to it's initial state.

This method will clear all the routes, mounts, error handlers, etc.

func (*App) Route

func (a *App) Route(pattern string, target Target) error

Map a function to a url pattern for any request method

func (*App) Run

func (a *App) Run(host string) error

func (*App) RunFcgi

func (a *App) RunFcgi(host string) error

func (*App) Serve

func (a *App) Serve(l net.Listener) error

func (*App) ServeFcgi

func (a *App) ServeFcgi(l net.Listener) error

func (*App) ServeHTTP

func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Context

type Context struct {
	Request  *http.Request
	Response *Response
	Get      url.Values
	Method   string
	Path     string
	Cookies  []*http.Cookie
}

Context wraps up all the data related to the request and makes it easier to access it.

func NewContext

func NewContext(r *http.Request) *Context

Create a new instance of Context

func (*Context) GetCookie

func (c *Context) GetCookie(name string) (string, error)

Return a cookie's value based on it's name

type CookieOptions

type CookieOptions struct {
	Path     string
	Domain   string
	MaxAge   int
	Secure   bool
	HttpOnly bool
}

func NewCookieOptions

func NewCookieOptions() *CookieOptions

func (*CookieOptions) Cookie

func (cc *CookieOptions) Cookie(name, value string) *http.Cookie

Creates a cookie with the parameters defined by the CookieOptions

func (*CookieOptions) DestroyCookie

func (cc *CookieOptions) DestroyCookie(name string) *http.Cookie

Creates a cookie that will destroy a cookie stored in the user-agent

type ErrorHandler

type ErrorHandler interface{}

An ErrorHandler is a function that allows you to customize what happens when errors occur.

Error handler's are associated with errors using the Error function.

uweb.Error(404, NotFoundHandler)

uweb.Error(500, SiteErrorHandler)

Error handlers can optionally accept a Context or the originating ErrorResponse

func NotFoundHandler(ctx *uweb.Context) string { ... }

func SiteErrorHandler(e *ErrorResponse) string { ... }

func MyErrorHandler(ctx *uweb.Context, e *ErrorResponse) *Response { ... }

Like Targets the return value for error handlers can be one of a variety of types: string, []byte, *Response, and io.Reader are all supported.

Finally, error handlers can return a value of any type that can be successfully converted into JSON using json.Marhsal.

type ErrorResponse

type ErrorResponse struct {
	Response
	Stack   string
	Message string
}

func NewError

func NewError(code int, message string) *ErrorResponse

func (*ErrorResponse) SetStack

func (e *ErrorResponse) SetStack(clean bool)

type Handler

type Handler interface {
	Handle(ctx *Context) *Response
}

type Response

type Response struct {
	Code         int
	Content      []byte
	WriteContent bool
	Cookies      map[string]*http.Cookie
	// contains filtered or unexported fields
}

Response represents a http response to a received request

func NewRedirect

func NewRedirect(url string, code int) *Response

func NewResponse

func NewResponse() *Response

func (*Response) DeleteCookie

func (r *Response) DeleteCookie(name string)

func (*Response) DeleteCookieWithOptions

func (r *Response) DeleteCookieWithOptions(name string, options *CookieOptions)

func (*Response) Header

func (r *Response) Header() http.Header

func (*Response) Merge

func (r *Response) Merge(resp *Response)

func (*Response) SetCookie

func (r *Response) SetCookie(name, value string)

func (*Response) SetCookieWithOptions

func (r *Response) SetCookieWithOptions(name, value string, options *CookieOptions)

func (*Response) StatusCode

func (r *Response) StatusCode() int

func (*Response) WriteResponse

func (r *Response) WriteResponse(w http.ResponseWriter)

type Target

type Target interface{}

A Target is a function that can process a request. Targets are passed into the methods Route, Get, Head, Post, etc.

app.Get("^path/to/handle/", MyTarget)

uweb.Route("^blog/([0-9)+)/edit/$", BlogEdit)

The simplest target has no inputs and no outputs:

func SimpleTarget() {
	Abort(404, "Page Not Found")
}

A more complex target might take the Context and args parsed from the url pattern and return a rendered string:

func MyTarget(ctx *uweb.Context, arg1, arg2 string) string {
	ctx.Response.Header().Set("Content-Type", "text/plain")
	return fmt.Sprintf("arg1: %s, arg2: %s", arg1, arg2)
}

uweb.Get("^([0-9]+)/([a-z-]+)/", MyTarget)

Additionally a target can be a variadic function, which is useful if the target is called with an varing number of arguments:

func MyTarget(args ...string) {
	...
}

The return value can be one of a variety of types: string, []byte, *Response, and io.Reader are all supported.

Finally, a target can return a value of any type that can be successfully converted into JSON using json.Marshal.

type MyStruct struct {
	Name string
}

func JSONTarget() MyStruct {
	return MyStruct{Name: "Joe Blogs"}
}

Notes

Bugs

  • consider refactoring this process into one that is more suited to being used in a variety of contexts.

  • add middleware/plugin capability

  • improve configurability

  • capture errors in non-debug mode

  • add more tests - query and post data

  • add ability to merge two Apps together

  • add ability to merge responses together

  • Form() and Query() methods in the context

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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