web

package module
v0.0.0-...-98f41ad Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2015 License: GPL-2.0 Imports: 20 Imported by: 0

README

GoDoc web

tiaotiao/web is a web server framework of golang.

Getting Started

Install:

# go get github.com/tiaotiao/web

A simple HelloWorld example:

package main

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 main() {
	w := web.NewWeb()
	w.Handle("GET", "/api/hello", Hello)
	w.ListenAndServe("tcp", ":8080")  // block forever until closed
}

Features

* Router
* Context
* Middleware
* ParseParams
* Scheme
* Response

Documentation

Index

Constants

View Source
const (
	StatusOK                  = http.StatusOK                  // 200
	StatusBadRequest          = http.StatusBadRequest          // 400
	StatusUnauthorized        = http.StatusUnauthorized        // 401
	StatusForbidden           = http.StatusForbidden           // 403
	StatusNotFound            = http.StatusNotFound            // 404
	StatusInternalServerError = http.StatusInternalServerError // 500
)
View Source
const (
	POST    = "POST"
	GET     = "GET"
	DELETE  = "DELETE"
	PUT     = "PUT"
	OPTIONS = "OPTIONS"
)

Variables

View Source
var HttpReadTimeout = time.Minute
View Source
var MaxBodyLength int64 = 20 * (1 << 20) // 20M
View Source
var ResultOK = Result{"result": "ok"}
View Source
var SchemeTagName = "web"

Tag name for Scheme.

Functions

func ParseParams

func ParseParams(c *Context) error

func Scheme

func Scheme(vals map[string]interface{}, dst interface{}) (err error)

func SchemeParam

func SchemeParam(vals map[string]interface{}, dst interface{}, tag string) (err error)

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

func (c *Context) Scheme(ptrArgs interface{}) error

func (*Context) SchemeBool

func (c *Context) SchemeBool(tag string) (v bool, err error)

func (*Context) SchemeInt

func (c *Context) SchemeInt(tag string) (v int, err error)

func (*Context) SchemeInt64

func (c *Context) SchemeInt64(tag string) (v int64, err error)

func (*Context) SchemeParam

func (c *Context) SchemeParam(ptrArg interface{}, tag string) error

func (*Context) SchemeString

func (c *Context) SchemeString(tag string) (v string, err error)

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 NewError

func NewError(e string, code int) *Error

func NewErrorMsg

func NewErrorMsg(e, msg string, code int) *Error

func (*Error) Error

func (e *Error) Error() string

func (*Error) StatusCode

func (e *Error) StatusCode() int

type Handler

type Handler interface{}

type Logger

type Logger interface {
	OnLog(r *http.Request, start time.Time, used time.Duration, code int, result interface{})
}

type Middleware

type Middleware interface {
	ServeMiddleware(c *Context) error
}

type MiddlewaresManager

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

func (*MiddlewaresManager) Append

type ResponseMiddleware

type ResponseMiddleware interface {
	ServeResponse(c *Context, result interface{}) (interface{}, error)
}

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 (r Result) SetStatusCode(code int) Result

func (Result) StatusCode

func (r Result) StatusCode() int

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 StdLogger

type StdLogger struct {
}

func NewStdLogger

func NewStdLogger() *StdLogger

func (*StdLogger) OnLog

func (l *StdLogger) OnLog(r *http.Request, start time.Time, used time.Duration, code int, result interface{})

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 NewWeb

func NewWeb() *Web

Create an Web object.

func (*Web) Append

func (w *Web) Append(midd Middleware)

Append a middleware. See Router.Append

func (*Web) Close

func (w *Web) Close()

Close all listeners and stop serve HTTP.

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

func (w *Web) Listen(protocol string, addr string) error

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

func (w *Web) ListenAndServe(protocol string, addr string) error

Listen an address and start to serve. Blocked until be closed or some error occurs. See Web.Listen and Web.Serve.

func (*Web) Serve

func (w *Web) Serve() error

Start to serve all listeners. It will block until all listeners closed.

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

func (w *Web) SetLogger(l Logger)

Set a logger to track request logs.

func (*Web) SetResponser

func (w *Web) SetResponser(r Responser)

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.

func (*Web) SubRouter

func (w *Web) SubRouter(pathPerfix string) Router

Get a sub router with the perfix path. See Router.SubRouter

type Writeable

type Writeable interface {
	OnWrite(w http.ResponseWriter) error
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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