wk

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

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

Go to latest
Published: Aug 15, 2013 License: Apache-2.0 Imports: 32 Imported by: 0

README

gwk

Web, Let's GO!

gwk is a smart & lightweight web server engine gwk is webkit for web server

Roadmap

  • 0.1 fork gomvc, refactoring. april 2013
  • 0.2 configration framework. april 2013
  • 0.3 web api server. april 2013
  • 0.4 test on go 1.1. may 2013
  • 0.5 cookie, session. may 2013
  • 0.6 view engine. may 2013
  • 0.7 watch & load config. june 2013
  • 1.x

Requirements

go 1.1

Usage

go get github.com/howeyc/fsnotify
go get github.com/sdming/kiss
go get github.com/sdming/mcache
go get github.com/sdming/wk

Document

Sorry for bad English,if you'd like to improve documents,please pull a request.

chinese document: https://github.com/sdming/wk/blob/master/cn.md

Demo

http://gwk-demo.appspot.com

Getting Started

// ./demo/basic/main.go for more detail

server, err := wk.NewDefaultServer()

if err != nil {
	fmt.Println("NewDefaultServer error", err)
	return
}

server.RouteTable.Get("/data/top/{count}").To(...)
server.RouteTable.Path("/basic#/{action}/{id}").ToController(...)

server.Start()

How to run demo

cd ./demo/basic  
go run main.go  

Route

Go cann't get parameter name of function by reflect, so it's a littel tricky to create parameters when call function by reflect.

// url: /demo/xxx/xxx
// route to controller
server.RouteTable.Path("/demo/{action}/{id}").ToController(controller)

// url: /data/top/10
// func: DataTopHandle(ctx *wk.HttpContext) (result wk.HttpResult, err error)
// route to func (*wk.HttpContext) (wk.HttpResult, error)
server.RouteTable.Get("/data/top/{count}").To(DataTopHandle)

// url: /data/int/1
// func: DataByInt(i int) *Data
// route to a function, convert parameter by index(p0,p1,p2...)
server.RouteTable.Get("/data/int/{p0}?").ToFunc(model.DataByInt)

// url: /data/range/1-9
// func: DataByIntRange(start, end int) []*Data
// route to a function, convert parameter by index(p0,p1,p2...)
server.RouteTable.Get("/data/range/{p0}-{p1}").ToFunc(model.DataByIntRange)

// url: /data/int/1/xml
// func: DataByInt(i int) *Data
// return xml
server.RouteTable.Get("/data/int/{p0}/xml").ToFunc(model.DataByInt).ReturnXml()

// url: /data/int/1/json
// func: DataByInt(i int) *Data
// return json
server.RouteTable.Get("/data/int/{p0}/json").ToFunc(model.DataByInt).ReturnJson()

// url: /data/int/1/kson
// func: DataByInt(i int) *Data
// return custome formatted data
server.RouteTable.Get("/data/int/{p0}/kson").ToFunc(model.DataByInt).Return(formatKson)

// url: /data/name/1
// func: DataByInt(i int) *Data
// route to a function, convert parameter by name
server.RouteTable.Get("/data/name/{id}").ToFunc(model.DataByInt).
	BindByNames("id")

// url: /data/namerange/1-9
// func: DataByIntRange(start, end int) []*Data
// route to a function, convert parameter by name
server.RouteTable.Get("/data/namerange/{start}-{end}").ToFunc(model.DataByIntRange).
	BindByNames("start", "end")

// url: /data/namerange/?start=1&end=9
// func: DataByIntRange(start, end int) []*Data
// route to a function, convert parameter by name
server.RouteTable.Get("/data/namerange/").ToFunc(model.DataByIntRange).
	BindByNames("start", "end")

// url: post /data/post?
// form:{"str": {"string"}, "uint": {"1024"}, "int": {"32"}, "float": {"1.1"}, "byte": {"64"}}
// func: DataPost(data Data) string 
// route http post to function, build struct parameter from form  
server.RouteTable.Post("/data/post?").ToFunc(model.DataPost).BindToStruct()

// url: post /data/postptr?
// form:{"str": {"string"}, "uint": {"1024"}, "int": {"32"}, "float": {"1.1"}, "byte": {"64"}}
// func DataPostPtr(data *Data) string
// route http post to function, build struct parameter from form
server.RouteTable.Post("/data/postptr?").ToFunc(model.DataPostPtr).BindToStruct()

// url: delete /data/delete/1
// func: DataDelete(i int) string 
// route http delete to function
server.RouteTable.Delete("/data/delete/{p0}").ToFunc(model.DataDelete)

// url: get /data/set?str=string&uint=1024&int=32&float=3.14&byte=64
// func: DataSet(s string, u uint64, i int, f float32, b byte) *Data 
// test diffrent parameter type
server.RouteTable.Get("/data/set?").ToFunc(model.DataSet).
	BindByNames("str", "uint", "int", "float", "byte")

Controller

Route url like "/demo/{action}" to T, call it's method by named {action}.

Current version only support method of type (*HttpContext) (result HttpResult, error)

// url: /demo/int/32
func (c *DemoController) Int(ctx *wk.HttpContext) (result wk.HttpResult, err error) {
	if id, ok := ctx.RouteData.Int("id"); ok {
		return wk.Json(c.getByInt(id)), nil
	}
	return wk.Data(""), nil
}

Formatter

If function doesn't return HttpResult, server will convert result to HttpResult according Accept of request. you can set Formatter for each function, or register global Formatter.

// return formatted (HttpResult, true) or return (nil, false) if doesn't format it
type FormatFunc func(*HttpContext, interface{}) (HttpResult, bool)

Configration

wk can manage configration for you. below is config example, more example at test/config_test.go

#app config file demo

#string
key_string: demo

#string
key_int: 	101

#bool
key_bool: 	true

#float
key_float:	3.14

#map
key_map:	{
	key1:	key1 value
	key2:	key2 value
}

#array
key_array:	[
	item 1		
	item 2
]

#struct
key_struct:	{
	Driver:		mysql			
	Host: 		127.0.0.1
	User:		user
	Password:	password			
}

#composite
key_config:	{	
	Log_Level:	debug
	Listen:		8000

	Roles: [
		{
			Name:	user
			Allow:	[
				/user		
				/order
			]
		} 
		{
			Name:	*				
			Deny: 	[
				/user
				/order
			]
		} 
	]

	Db_Log:	{
		Driver:		mysql			
		Host: 		127.0.0.1
		User:		user
		Password:	password
		Database:	log
	}

	Env:	{
		auth:		http://auth.io
		browser:	ie, chrome, firefox, safari
	}
}

Session

Example of session: ./demo/basic/controller/session.go

By default, session store in memory(mcache), if you want to store somewhere else(redis, memcahe...), need to:

  1. implement interface: session.Driver
  2. call session.Register to register it
  3. set SessionDriver of web.conf

Basic Conception

HttpContext is wrap of http.Request & http.Response

HttpProcessor handle request and build HttpResult(maybe)

type HttpProcessor interface {
	Execute(ctx *HttpContext)

	// Register is called once when server init  
	Register(server *HttpServer)
}

HttpResult know how to write http.Response

type HttpResult interface {
	Execute(ctx *HttpContext)
}

The lifecyle is

  1. receive request, create HttpContext
  2. run each HttpProcessor
  3. execute HttpResult

HttpProcessor

You can add or remove HttpProcessor before server starting.

type ProcessTable []*Process

func (pt *ProcessTable) Append(p *Process)

func (pt *ProcessTable) Remove(name string)

func (pt *ProcessTable) Insert(p *Process, index int) 

http result

  • ContentResult: html raw
  • JsonResult: application/json
  • XmlResult: application/xml
  • JsonpResult: application/jsonp
  • ViewResult view
  • FileResult static file
  • FileStreamResult stream file
  • RedirectResult redirect
  • NotFoundResult 404
  • ErrorResult error
  • BundleResult bundle of files

Event

Call Fire() to fire an event

Fire(moudle, name string, source, data interface{}, context *HttpContext) 

Call On() to listen events

On(moudle, name string, handler Subscriber) 

View engine

Template Funcs

  • eq: equal
  • eqs: compare as string
  • get: greater
  • le: less
  • set: set map[string]interface{}
  • raw: unescaped html
  • incl: include or not
  • selected: return "selected" or ""
  • checked: return "checked" or ""
  • nl2br: replace "\n" with "<br/>"
  • jsvar: create javascript variable, like var name = {...}
  • import: import a template file
  • partial: call a template

you can find examples in folder "./test/views/" or "./demo/basic/views/"

Example

  • basic example
    run default http server
    file: ./demo/basic/main.go

  • rest api example
    run rest http api server
    file: ./demo/rest/main.go

  • httpresult example
    how to write a http result to return qrcode image
    file: ./demo/basic/model/qr.go

  • event example
    how to listen events
    file: ./demo/basic/model/event.go

  • custom processor
    how to register a Processor to compress http response
    file: ./compress.go

  • file stream example
    how to return a file stream
    file: ./demo/basic/model/file.go

    how to bundling several js files into one file file: ./demo/basic/model/file.go

  • BigPipe example
    how to simulate BigPipe & comet
    file: ./demo/basic/model/bigpipe.go (need fix bug?)

  • session example
    how to add, get,remove... session file: ./demo/basic/controller/session.go

  • view example
    how to use viewengine
    file: ./demo/basic/controller/user.go

  • GAE example
    how to deploy on GAE
    file: ./demo/gae

ORM

Maybe, maybe not. don't have a plan yet. focus on web server.

Validation

No

Cache, gzip

nginx, haproxy, Varnish can provide awesome service

Contributing

  • github.com/sdming

License

Apache License 2.0

About

Documentation

Index

Constants

View Source
const (
	HttpVerbsGet     = "GET"
	HttpVerbsPost    = "POST"
	HttpVerbsPut     = "PUT"
	HttpVerbsDelete  = "DELETE"
	HttpVerbsHead    = "HEAD"
	HttpVerbsTrace   = "TRACE"
	HttpVerbsConnect = "CONNECT"
	HttpVerbsOptions = "OPTIONS"
)
View Source
const (
	HeaderAccept          = "Accept"
	HeaderAcceptCharset   = "Accept-Charset"
	HeaderAcceptEncoding  = "Accept-Encoding"
	HeaderCacheControl    = "Cache-Control"
	HeaderContentEncoding = "Content-Encoding"
	HeaderContentLength   = "Content-Length"
	HeaderContentType     = "Content-Type"
	HeaderDate            = "Date"
	HeaderEtag            = "Etag"
	HeaderExpires         = "Expires"
	HeaderLastModified    = "Last-Modified"
	HeaderLocation        = "Location"
	HeaderPragma          = "Pragma"
	HeaderServer          = "Server"
	HeaderSetCookie       = "Set-Cookie"
	HeaderUserAgent       = "User-Agent"
)
View Source
const (
	ContentTypeStream     = "application/octet-stream"
	ContentTypeJson       = "application/json"
	ContentTypeJsonp      = "application/jsonp"
	ContentTypeJavascript = "application/javascript"
	ContentTypeHTML       = "text/html"
	ContentTypeXml        = "text/xml"
	ContentTypeCss        = "text/css"
	ContentTypeText       = "text/plain"
	ContentTypeGif        = "image/gif"
	ContentTypeIcon       = "image/x-icon"
	ContentTypeJpeg       = "image/jpeg"
	ContentTypePng        = "image/png"
)
View Source
const (
	LogError = iota
	LogInfo
	LogDebug
)

Variables

View Source
var (
	// logger
	Logger *log.Logger

	// LogLevel is level of log
	LogLevel int = LogError

	// EnableProfile mean enable http profile or not
	EnableProfile bool = false
)
View Source
var SessionDriver session.Driver
View Source
var (
	Subscribers []*SubscriberItem
)
View Source
var (
	TemplateFuncs template.FuncMap = make(map[string]interface{})
)

Functions

func On

func On(moudle, name string, handler Subscriber)

On register event lister

func OnFunc

func OnFunc(moudle, name string, handler func(*EventContext))

On register event lister

func RegisterProcessor

func RegisterProcessor(name string, p HttpProcessor)

RegisterProcessor append a HttpProcessor to global ProcessTable

func RegisterProcessorWith

func RegisterProcessorWith(name string, p HttpProcessor, method, path string)

RegisterProcessorWith append a HttpProcessor to global ProcessTable, with field method and path

Types

type ActionContext

type ActionContext struct {
	// Name is action method name
	Name       string
	Context    *HttpContext
	Controller reflect.Value
	Result     HttpResult
	Err        error
}

ActionContext is data that pass to ActionSubscriber

type ActionSubscriber

type ActionSubscriber interface {
	OnActionExecuting(action *ActionContext)
	OnActionExecuted(action *ActionContext)
	OnException(action *ActionContext)
}

ActionSubscriber is interface that subscrib controller events

type BundleResult

type BundleResult struct {
	Files []string
}

BundleResult is bundle of Files

func (*BundleResult) Execute

func (b *BundleResult) Execute(ctx *HttpContext) error

Execute write content of files to HttpContext.Response

func (*BundleResult) Type

func (b *BundleResult) Type() string

ContentType return mime type of BundleResult.Files[0]

type ChanResult

type ChanResult struct {
	Wait        sync.WaitGroup
	Chan        chan string
	ContentType string
	Start       []byte
	End         []byte
	Timeout     time.Duration
}

ChanResult read from a chan string, then write to response

func (*ChanResult) Execute

func (c *ChanResult) Execute(ctx *HttpContext) error

Execute read from Chan then write to Response, until Wait done

type CompressProcessor

type CompressProcessor struct {
	Enable   bool
	Level    int
	MimeType string
}

CompressProcessor compress http response with gzip/deflate TODO: filter by MimeType?

func (*CompressProcessor) Execute

func (cp *CompressProcessor) Execute(ctx *HttpContext)

Execute convert ctx.Response to compressResponseWriter

func (*CompressProcessor) Register

func (cp *CompressProcessor) Register(server *HttpServer)

Register initialize CompressProcessor

type ContentResult

type ContentResult struct {

	// ContentType
	ContentType string

	// Data
	Data interface{}
}

ContentResult is raw content

func Content

func Content(data interface{}, contentType string) *ContentResult

Content return *ContentResult

func (*ContentResult) Execute

func (c *ContentResult) Execute(ctx *HttpContext) error

Execute write Data to response

type ContentTyper

type ContentTyper interface {
	Type() string
}

type Controller

type Controller struct {

	// Handler
	Handler reflect.Value

	//Methods is cache of method reflect info
	Methods map[string]*gotype.MethodInfo
	// contains filtered or unexported fields
}

Controller is wrap of controller handler

func (*Controller) Execute

func (c *Controller) Execute(ctx *HttpContext)

Execute call action method

type DataResult

type DataResult struct {

	// Data
	Data interface{}
}

DataResult is wrap of simple type

func Data

func Data(data interface{}) *DataResult

Data return *DataResult

func (*DataResult) Execute

func (c *DataResult) Execute(ctx *HttpContext) error

Execute write Data to response

type ErrorResult

type ErrorResult struct {
	Message string
	Stack   []byte
	State   interface{}
}

ErrorResult return error to client

func Error

func Error(message string) *ErrorResult

Error return *ErrorResult

func (*ErrorResult) Execute

func (e *ErrorResult) Execute(ctx *HttpContext) error

Execute write response

func (*ErrorResult) String

func (e *ErrorResult) String() string

String

type EventContext

type EventContext struct {
	Moudle  string
	Name    string
	Source  interface{}
	Data    interface{}
	Context *HttpContext
}

EventContext is the data pass to Subscriber

func (*EventContext) String

func (e *EventContext) String() string

String

type FileResult

type FileResult struct {
	Path string
}

FileResult is wrap of static file

func File

func File(path string) *FileResult

File return *FileResult

func (*FileResult) Execute

func (file *FileResult) Execute(ctx *HttpContext) error

Execute replies to the request with the contents of FileResult.Path

func (*FileResult) String

func (file *FileResult) String() string

String

func (*FileResult) Type

func (file *FileResult) Type() string

ContentType return mime type of file

type FileStreamResult

type FileStreamResult struct {
	// ContentType
	ContentType string

	DownloadName string

	ModifyTime time.Time

	// Data ?Data io.ReadSeeker
	Data io.Reader
}

FileStreamResult

func FileStream

func FileStream(contentType, downloadName string, reader io.Reader, modtime time.Time) *FileStreamResult

FileStream return *FileStream

func (*FileStreamResult) Execute

func (file *FileStreamResult) Execute(ctx *HttpContext) error

func (*FileStreamResult) Type

func (file *FileStreamResult) Type() string

ContentType return mime type of file

type FormatFunc

type FormatFunc func(*HttpContext, interface{}) (HttpResult, bool)

FormatFunc return formatted HttpResult or return (nil, false) if doesn't format it

type FormatList

type FormatList []FormatFunc

FormatList

var Formatters FormatList

func (*FormatList) Append

func (f *FormatList) Append(fn FormatFunc)

Append register a FormatFunc

func (*FormatList) Remove

func (f *FormatList) Remove(fn FormatFunc)

Remove unregister FormatFunc

type FuncServer

type FuncServer struct {
	Binder func(*HttpContext) ([]reflect.Value, error)
	Func   interface{}

	Formatter FormatFunc
	// contains filtered or unexported fields
}

FuncServer is wrap of route handle function

func (*FuncServer) BindByIndex

func (f *FuncServer) BindByIndex()

BindByIndex create function parameters from p1,p2,p3...

func (*FuncServer) BindByNames

func (f *FuncServer) BindByNames(name ...string)

BindByNames create function parameters from name

func (*FuncServer) BindToStruct

func (f *FuncServer) BindToStruct()

BindToStruct create struct parameters

func (*FuncServer) Execute

func (f *FuncServer) Execute(ctx *HttpContext)

Execute call function through reflect

func (*FuncServer) Return

func (f *FuncServer) Return(fn FormatFunc) *FuncServer

Return format result by FormatFunc

func (*FuncServer) ReturnJson

func (f *FuncServer) ReturnJson() *FuncServer

ReturnJson format result as Json

func (*FuncServer) ReturnXml

func (f *FuncServer) ReturnXml() *FuncServer

ReturnXml format result as Xml

type GoHtml

type GoHtml struct {
	BasePath       string
	EnableCache    bool
	TemplatesCache map[string]*template.Template
	Funcs          template.FuncMap

	sync.Mutex
	// contains filtered or unexported fields
}

GoHtml is a ViewEngine that wrap "html/template"

func NewGoHtml

func NewGoHtml(basePath string) (*GoHtml, error)

NewGoHtml return a *GoHtml, it retur error if basePath doesn't exists

func (*GoHtml) AddTemplate

func (ve *GoHtml) AddTemplate(name string, t *template.Template) error

func (*GoHtml) Execte

func (ve *GoHtml) Execte(wr io.Writer, file string, data interface{}) error

Execte execute template

func (*GoHtml) Register

func (ve *GoHtml) Register(server *HttpServer) error

Register initialize viewengine

func (*GoHtml) String

func (ve *GoHtml) String() string

String

type Handler

type Handler interface {
	Execute(ctx *HttpContext)
}

type HtmlOption

type HtmlOption struct {
	Text  string
	Value string
}

type HttpContext

type HttpContext struct {
	// Server is current http server
	Server *HttpServer

	// Request is *http.Request
	Request *http.Request

	// Resonse is http.ResponseWriter
	Resonse http.ResponseWriter

	// Method is http method
	Method string

	// RequestPath is
	RequestPath string

	// PhysicalPath is path of static file
	PhysicalPath string

	// RouteData
	RouteData RouteData

	// ViewData
	ViewData map[string]interface{}

	// Result
	Result HttpResult

	// Error
	Error error

	// Flash is flash variables of request life cycle
	Flash map[string]interface{}

	// Session
	Session Session

	// SessionIsNew is true if create session in this request
	SessionIsNew bool
}

HttpContext is wrap of request & response

func (*HttpContext) Accept

func (ctx *HttpContext) Accept() string

Accept return request header Accept

func (*HttpContext) AddHeader

func (ctx *HttpContext) AddHeader(key string, value string)

AddHeader add response http header

func (*HttpContext) ContentType

func (ctx *HttpContext) ContentType(ctype string)

ContentType set response header Content-Type

func (*HttpContext) Cookie

func (ctx *HttpContext) Cookie(name string) (*http.Cookie, error)

Cookie return cookie from request

func (*HttpContext) Expires

func (ctx *HttpContext) Expires(t string)

Expires set reponse header Expires

func (*HttpContext) FV

func (ctx *HttpContext) FV(name string) string

FV is alias of FormValue

func (*HttpContext) Flush

func (ctx *HttpContext) Flush()

Flush flush response immediately

func (*HttpContext) FormBool

func (ctx *HttpContext) FormBool(name string) (bool, bool)

FormBool parse form value as bool

func (*HttpContext) FormBoolOr

func (ctx *HttpContext) FormBoolOr(name string, v bool) bool

FormBoolOr return form value as bool or v

func (*HttpContext) FormFloat

func (ctx *HttpContext) FormFloat(name string) (float64, bool)

FormFloat parse form value as float64

func (*HttpContext) FormFloatOr

func (ctx *HttpContext) FormFloatOr(name string, v float64) float64

FormFloatOr return form value as float64 or v

func (*HttpContext) FormInt

func (ctx *HttpContext) FormInt(name string) (int, bool)

FormInt parse form value as int

func (*HttpContext) FormIntOr

func (ctx *HttpContext) FormIntOr(name string, v int) int

FormIntOr return form value as int or v

func (*HttpContext) FormValue

func (ctx *HttpContext) FormValue(name string) string

FormValue is alias of Request FormValue

func (*HttpContext) GetFlash

func (ctx *HttpContext) GetFlash(key string) (v interface{}, ok bool)

GetFlash return value in Context.Flash

func (*HttpContext) ReadBody

func (ctx *HttpContext) ReadBody() ([]byte, error)

ReadBody read Request.Body

func (*HttpContext) ReqHeader

func (ctx *HttpContext) ReqHeader(name string) string

ReqHeader return request header by name

func (*HttpContext) ResHeader

func (ctx *HttpContext) ResHeader(name string) string

ResHeader return response header by name

func (*HttpContext) RouteValue

func (ctx *HttpContext) RouteValue(name string) (string, bool)

RouteValue return route value by name

func (*HttpContext) SessionId

func (ctx *HttpContext) SessionId() string

SessionId return sessionid of current context

func (*HttpContext) SetCookie

func (ctx *HttpContext) SetCookie(cookie *http.Cookie)

SetCookie set cookie to response

func (*HttpContext) SetFlash

func (ctx *HttpContext) SetFlash(key string, v interface{})

SetFlash set value to Context.Flash

func (*HttpContext) SetHeader

func (ctx *HttpContext) SetHeader(key string, value string)

SetHeader set resonse http header

func (*HttpContext) Status

func (ctx *HttpContext) Status(code int)

Status write status code to http header

func (*HttpContext) String

func (ctx *HttpContext) String() string

String

func (*HttpContext) Write

func (ctx *HttpContext) Write(b []byte) (int, error)

Write writes b to resposne

type HttpProcessor

type HttpProcessor interface {
	// Execute handle request
	Execute(ctx *HttpContext)

	// Register is called once when create a new HttpServer
	Register(server *HttpServer)
}

HttpProcessor is interface that handle http request

type HttpResult

type HttpResult interface {
	// Execute
	Execute(ctx *HttpContext) error
}

HttpResult is a interface that define how to write server reply to response

type HttpServer

type HttpServer struct {
	// config
	Config *WebConfig

	// net.Listener
	Listener net.Listener

	// Processes
	Processes ProcessTable

	// RouteTable
	RouteTable *RouteTable

	//server variables
	Variables map[string]interface{}

	// ViewEngine
	ViewEngine ViewEngine
	// contains filtered or unexported fields
}

HttpServer

func NewDefaultServer

func NewDefaultServer() (srv *HttpServer, err error)

DefaultServer return a http server with default config

func NewHttpServer

func NewHttpServer(config *WebConfig) (srv *HttpServer, err error)

NewHttpServer return a http server with provided config

func (*HttpServer) Fire

func (srv *HttpServer) Fire(moudle, name string, source, data interface{}, context *HttpContext)

Fire can fire a event

func (*HttpServer) InnerServer

func (srv *HttpServer) InnerServer() *http.Server

InnerServer return inner embedded *http.Server

func (*HttpServer) MapPath

func (srv *HttpServer) MapPath(file string) string

MapPath return physical path

func (*HttpServer) ServeHTTP

func (srv *HttpServer) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP

func (*HttpServer) Setup

func (srv *HttpServer) Setup() (err error)

Setup initialize server instance

func (*HttpServer) Start

func (srv *HttpServer) Start() (err error)

Start start server instance and listent request

type JsonResult

type JsonResult struct {
	NeedIndent bool
	Data       interface{}
	// contains filtered or unexported fields
}

JsonResult marshal data and write to response ContentType is "application/json"

func Json

func Json(a interface{}) *JsonResult

Json return *JsonResult

func (*JsonResult) Execute

func (j *JsonResult) Execute(ctx *HttpContext) error

Execute encode result as json and write to response

func (*JsonResult) Type

func (j *JsonResult) Type() string

ContentType return "application/json"

func (*JsonResult) Write

func (j *JsonResult) Write(header http.Header, body io.Writer) error

WriteTo writes marshaled data to w

type JsonpResult

type JsonpResult struct {
	Data interface{}
}

JsonpResult

func (*JsonpResult) Execute

func (j *JsonpResult) Execute(ctx *HttpContext) error

Execute Content-Type is application/javascript

type NotFoundResult

type NotFoundResult struct {
}

NotFoundResult is wrap of http 404

func (*NotFoundResult) Execute

func (r *NotFoundResult) Execute(ctx *HttpContext) error

Execute return 404 to client

type NotModifiedResult

type NotModifiedResult struct {
}

NotModifiedResult is wrap of http.StatusNotModified

func (*NotModifiedResult) Execute

func (r *NotModifiedResult) Execute(ctx *HttpContext) error

Execute

type Process

type Process struct {
	// Name
	Name string

	// Path is url to match, / or empty to match all
	// change to regex? containers muti ?
	Path string

	// Method is http method to match, * or empty to match all
	Method string

	// Handler is the HttpProcessor
	Handler HttpProcessor
}

Process is wrap of HttpProcessor

func NewCompressProcess

func NewCompressProcess(name, method, path string) *Process

NewCompressProcess return a *Process that wrap CompressProcessor

type ProcessTable

type ProcessTable []*Process

ProcessTable is alias of []*Process

var Processes ProcessTable

Processes is global ProcessTable configration

func (*ProcessTable) Append

func (pt *ProcessTable) Append(p *Process)

Append add a *Process at end

func (*ProcessTable) InsertAfter

func (pt *ProcessTable) InsertAfter(name string, p *Process)

InsertAfter add a *Process after name

func (*ProcessTable) InsertBefore

func (pt *ProcessTable) InsertBefore(name string, p *Process)

InsertBefore add a *Process before name

func (*ProcessTable) Remove

func (pt *ProcessTable) Remove(name string)

Remove delete a *Process from ProcessTable

type RedirectResult

type RedirectResult struct {
	// Permanent mean redirect permanent or not
	Permanent bool

	// UrlStr is the url to redirect
	UrlStr string
}

RedirectResult is wrap of http.StatusMovedPermanently or http.StatusFound

func Redirect

func Redirect(urlStr string, permanent bool) *RedirectResult

func (*RedirectResult) Execute

func (r *RedirectResult) Execute(ctx *HttpContext) error

Execute write status code http.StatusMovedPermanently or http.StatusFound

type Render

type Render interface {
	ContentTyper

	// Write write header & body
	Write(header http.Header, body io.Writer) error
}

type RenderProcessor

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

RenderProcessor render http result

func (*RenderProcessor) Execute

func (p *RenderProcessor) Execute(ctx *HttpContext)

Execute render http result to response

func (*RenderProcessor) Register

func (p *RenderProcessor) Register(server *HttpServer)

Register

type RouteData

type RouteData map[string]string

RouteData is wrap of route data

func (RouteData) Bool

func (r RouteData) Bool(name string) (bool, bool)

Bool parse route value as bool

func (RouteData) BoolOr

func (r RouteData) BoolOr(name string, v bool) bool

BoolOr return route value as bool or v

func (RouteData) Float

func (r RouteData) Float(name string) (float64, bool)

Float parse route value as float64

func (RouteData) FloatOr

func (r RouteData) FloatOr(name string, v float64) float64

FloatOr return route value as float64 or v

func (RouteData) Int

func (r RouteData) Int(name string) (int, bool)

Int parse route value as int

func (RouteData) IntOr

func (r RouteData) IntOr(name string, v int) int

Int return route value as int or v

func (RouteData) Str

func (r RouteData) Str(name string) (string, bool)

Str return route value

func (RouteData) StrOr

func (r RouteData) StrOr(name string, v string) string

Str return route value or v if name donesn't exist

type RouteFunc

type RouteFunc func(*HttpContext) (HttpResult, error)

RouteFunc is wrap of func(*HttpContext) (HttpResult, error)

func (RouteFunc) Execute

func (f RouteFunc) Execute(ctx *HttpContext)

Execute

type RouteProcessor

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

RouteProcessor route request to handler

func (*RouteProcessor) Execute

func (r *RouteProcessor) Execute(ctx *HttpContext)

Execute find matched RouteRule and call it's Handler

func (*RouteProcessor) Register

func (r *RouteProcessor) Register(server *HttpServer)

Register

type RouteRule

type RouteRule struct {

	// Methos is http method of request
	Method string

	// Pattern is path pattern
	Pattern string

	// Handler process request
	Handler Handler
	// contains filtered or unexported fields
}

RouteRule is set of route rule & handler

func (*RouteRule) HandleBy

func (r *RouteRule) HandleBy(handler Handler)

HandleBy route reuqest to handler

func (*RouteRule) Match

func (r *RouteRule) Match(ctx *HttpContext) (data RouteData, ok bool)

Match return (route data,true) if matched, or (nil, false) if not

func (*RouteRule) String

func (r *RouteRule) String() string

String

func (*RouteRule) To

func (r *RouteRule) To(handler func(*HttpContext) (HttpResult, error))

To route reuqest to a function func(*HttpContext) (HttpResult, error)

func (*RouteRule) ToController

func (r *RouteRule) ToController(controller interface{}) *Controller

ToController route request to an Controller

func (*RouteRule) ToFunc

func (r *RouteRule) ToFunc(function interface{}) *FuncServer

ToFunc route reuqest to a function

type RouteTable

type RouteTable struct {
	Routes []*RouteRule
}

RouteTable is collection of RouteRule

func (*RouteTable) Delete

func (r *RouteTable) Delete(path string) *RouteRule

Delete match Delete & path

func (*RouteTable) Get

func (r *RouteTable) Get(path string) *RouteRule

Get match Get & HttpVerbs

func (*RouteTable) Match

func (r *RouteTable) Match(ctx *HttpContext) (rule *RouteRule, data map[string]string, ok bool)

Match return matched *RouteRule and route data

func (*RouteTable) Path

func (r *RouteTable) Path(path string) *RouteRule

Path match path

func (*RouteTable) Post

func (r *RouteTable) Post(path string) *RouteRule

Post match Post & path

func (*RouteTable) Put

func (r *RouteTable) Put(path string) *RouteRule

Put match Put & HttpVerbs

func (*RouteTable) Regexp

func (r *RouteTable) Regexp(method, path string) *RouteRule

Regexp match with regexp

type Session

type Session string

func (Session) Abandon

func (s Session) Abandon() error

func (Session) Add

func (s Session) Add(key string, value interface{}) (bool, error)

func (Session) Get

func (s Session) Get(key string) (interface{}, bool, error)

func (Session) Keys

func (s Session) Keys() ([]string, error)

func (Session) Remove

func (s Session) Remove(key string) error

func (Session) Set

func (s Session) Set(key string, value interface{}) error

type StaticProcessor

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

StaticProcessor handle request of static file

func (*StaticProcessor) Execute

func (p *StaticProcessor) Execute(ctx *HttpContext)

Execute set FileResult if request file does exist

func (*StaticProcessor) Register

func (p *StaticProcessor) Register(server *HttpServer)

Register

type Subscriber

type Subscriber interface {
	On(e *EventContext)
}

Subscriber is interface of event listener

type SubscriberFunc

type SubscriberFunc func(*EventContext)

SubscriberFunc

func (SubscriberFunc) On

func (f SubscriberFunc) On(e *EventContext)

On implement Subscriber

type SubscriberItem

type SubscriberItem struct {
	Moudle  string
	Name    string
	Handler Subscriber
}

SubscriberItem is wrap of Subscriber

type TextResult

type TextResult string

TextResult is plaintext

func Text

func Text(data string) TextResult

Text return a *TextResult

func (TextResult) Execute

func (t TextResult) Execute(ctx *HttpContext) error

Execute write Data to response

type ViewData

type ViewData map[string]interface{}

type ViewEngine

type ViewEngine interface {
	Register(server *HttpServer) error
	Execte(writer io.Writer, file string, data interface{}) error
}

ViewEngine is wrap of executing template file

type ViewResult

type ViewResult struct {
	File string
}

ViewResult

func View

func View(file string) *ViewResult

View return *ViewResult

func (*ViewResult) Execute

func (v *ViewResult) Execute(ctx *HttpContext) error

Execute

func (*ViewResult) String

func (v *ViewResult) String() string

String

func (*ViewResult) Type

func (v *ViewResult) Type() string

ContentType return mime type

type VoidResult

type VoidResult struct {
}

VoidResult represents a result that doesn't do anything

func (*VoidResult) Execute

func (r *VoidResult) Execute(ctx *HttpContext) error

Execute

type WebConfig

type WebConfig struct {
	// ServerKey is the identify of server
	ServerKey string

	// Address is the address to listen
	Address string

	// RootDir is the route directory of web application
	RootDir string

	// Timeout is timeout of http handle in second
	Timeout int

	// PublicDir is directory of static files
	PublicDir string

	// ConfigDir is directory of config files
	ConfigDir string

	// ViewDir is base directory of views
	ViewDir string

	// AppConfig is app configuration data
	AppConfig *kson.Node

	// PluginConfig is configuration data of plugins
	PluginConfig *kson.Node

	// ReadTimeout is maximum duration before timing out read of the request, in second
	ReadTimeout int

	// WriteTimeout is maximum duration before timing out write of the response, in second
	WriteTimeout int

	// MaxHeaderBytes is maximum size of request headers
	MaxHeaderBytes int

	// SessionEnable is true if enable session
	SessionEnable bool

	// SessionTimeout, session timeout in second
	SessionTimeout int

	// SessionDriver is the name of driver
	SessionDriver string

	// ViewEnable, enable view engine or not
	ViewEnable bool

	// IndexesEnable like Indexes of apache
	IndexesEnable bool

	// NotFoundPageEnable
	NotFoundPageEnable bool

	// ErrorPageEnable
	ErrorPageEnable bool

	// Debug is true if run in debug model
	Debug bool
	// contains filtered or unexported fields
}

WebConfig is configuration of go web server

func ConfigFromFile

func ConfigFromFile(file string) (conf *WebConfig, err error)

ConfigFromFile parse file and return *WebConfig

func NewDefaultConfig

func NewDefaultConfig() *WebConfig

NewDefaultConfig return *WebConfig with default value

func ReadDefaultConfigFile

func ReadDefaultConfigFile() (conf *WebConfig, err error)

ReadDefaultConfigFile parse default config file and return *WebConfig

func (*WebConfig) String

func (conf *WebConfig) String() string

String

type XmlResult

type XmlResult struct {
	Data       interface{}
	NeedIndent bool
	// contains filtered or unexported fields
}

XmlResult marshal data to xml and write to response ContentType: "application/xml"

func Xml

func Xml(a interface{}) *XmlResult

Xml return *XmlResult

func (*XmlResult) Execute

func (x *XmlResult) Execute(ctx *HttpContext) error

Execute encode result as xml and write to response

func (*XmlResult) Type

func (x *XmlResult) Type() string

func (*XmlResult) Write

func (x *XmlResult) Write(header http.Header, body io.Writer) error

WriteTo writes marshaled data to w

Directories

Path Synopsis
demo
basic
basic demo`
basic demo`
basic/boot
boot
boot
basic/controller
basic basic basic basic basic demo basic basic session demo basic demo
basic basic basic basic basic demo basic basic session demo basic demo
basic/model
basic demo
basic demo
rest
rest web api demo
rest web api demo
rest/controller
basic basic
basic basic

Jump to

Keyboard shortcuts

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