asana

package module
v1.14.0 Latest Latest
Warning

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

Go to latest
Published: May 11, 2020 License: Apache-2.0 Imports: 44 Imported by: 0

README

Asana Build Status GoDoc Go Report Card

Asana is a framework based on Beego (fork).

Quick Start

Download and install
go get github.com/goasana/[email protected]
Create file hello.go
package main

import "github.com/goasana/asana"

func main(){
    asana.Run()
}
Build and run
go build hello.go
./hello
Go to http://localhost:8080

Congratulations! You've just built your first Asana app.

Features

  • YAML file default config
  • Kubernetes Map, File, Etcd, Consul, etc. config providers.
  • Redis, Memcached, ssdb, gCache and local cache.
  • RESTful support.
  • Good for Microservices, RESTful protocol buffers with gogo/protobuf
  • MVC architecture
  • Modularity
  • Auto API documents
  • Annotation router
  • Namespace
  • Powerful development tools
  • Full stack for Web & API

License

Asana source code is licensed under the Apache Licence, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html).

Documentation

Overview

Package asana provide a MVC framework asana: an open-source, high-performance, modular, full-stack web framework

It is used for rapid development of RESTful APIs, web apps and backend services in Go. asana is inspired by Tornado, Sinatra and Flask with the added benefit of some Go-specific features such as interfaces and struct embedding.

package main
import "github.com/goasana/asana"

func main() {
 asana.Run()
}

more information: http://asana.me

Index

Constants

View Source
const (
	// VERSION represent asana web framework version.
	VERSION = "1.14.0"

	// DEV is for develop
	DEV = "dev"
	// PROD is for production
	PROD = "prod"
)
View Source
const (
	LevelEmergency = iota
	LevelAlert
	LevelCritical
	LevelError
	LevelWarning
	LevelNotice
	LevelInformational
	LevelDebug
)

Log levels to control the logging output. Deprecated: use github.com/goasana/asana/logs instead.

View Source
const (
	BeforeStatic = iota
	BeforeRouter
	BeforeExec
	AfterExec
	FinishRouter
)

default filter execution points

Variables

View Source
var (
	// BConfig is the default config for Application
	BConfig *Config
	// AppConfig is the instance of Config, store the config information from file
	AppConfig *asanaAppConfig
	// AppPath is the absolute path to the app
	AppPath string
	// GlobalSessions is the instance for the session manager
	GlobalSessions *session.Manager
)
View Source
var (
	// ErrAbort custom error when user stop request handler manually.
	ErrAbort = errors.New("user stop run")
	// GlobalControllerRouter store comments with controller. pkgpath controller:comments
	GlobalControllerRouter = make(map[string][]ControllerComments)
)
View Source
var AsanaLogger = logs.GetAsanaLogger()

AsanaLogger references the used application logger. Deprecated: use github.com/goasana/asana/logs instead.

View Source
var ErrorMaps = make(map[string]*errorInfo, 10)

ErrorMaps holds map of http handlers for each error string. there is 10 kinds default error(40x and 50x)

View Source
var FilterMonitorFunc func(string, string, time.Duration, string, int) bool

FilterMonitorFunc is default monitor filter when admin module is enable. if this func returns, admin module records qps for this request by condition of this function logic. usage:

func MyFilterMonitor(method, requestPath string, t time.Duration, pattern string, statusCode int) bool {
 	if method == "POST" {
		return false
 	}
 	if t.Nanoseconds() < 100 {
		return false
 	}
 	if strings.HasPrefix(requestPath, "/asana") {
		return false
 	}
 	return true
}
asana.FilterMonitorFunc = MyFilterMonitor.

Functions

func AddAPPStartHook

func AddAPPStartHook(hf ...hookFunc)

AddAPPStartHook is used to register the hookFunc The hookfuncs will run in asana.Run() such as initiating session , starting middleware , building template, starting admin control and so on.

func AddFuncMap

func AddFuncMap(key string, fn interface{}) error

AddFuncMap let user to register a func in the template.

func AddNamespace

func AddNamespace(nl ...*Namespace)

AddNamespace register Namespace into asana.Handler support multi Namespace

func AddTemplateExt

func AddTemplateExt(ext string)

AddTemplateExt add new extension for template.

func AddViewPath

func AddViewPath(viewPath string) error

AddViewPath adds a new path to the supported view paths. Can later be used by setting a controller ViewPath to this folder will panic if called after asana.Run()

func Alert

func Alert(v ...interface{})

Alert logs a message at alert level. Deprecated: use github.com/goasana/asana/logs instead.

func AssetsCSS

func AssetsCSS(text string) template.HTML

AssetsCSS returns stylesheet link tag with src string.

func AssetsJs

func AssetsJs(text string) template.HTML

AssetsJs returns script tag with src string.

func BuildTemplate

func BuildTemplate(dir string, files ...string) error

BuildTemplate will build all template files in a directory. it makes asana can render any template file in view directory.

func Compare

func Compare(a, b interface{}) (equal bool)

Compare is a quick and dirty comparison function. It will convert whatever you give it to strings and see if the two values are equal. Whitespace is trimmed. Used by the template parser as "eq".

func CompareNot

func CompareNot(a, b interface{}) (equal bool)

CompareNot !Compare

func Critical

func Critical(v ...interface{})

Critical logs a message at critical level. Deprecated: use github.com/goasana/asana/logs instead.

func Date

func Date(t time.Time, format string) string

Date takes a PHP like date func to Go's time format.

func DateFormat

func DateFormat(t time.Time, layout string) (dateString string)

DateFormat takes a time and a layout string and returns a string with the formatted date. Used by the template parser as "dateformat"

func DateParse

func DateParse(dateString, format string) (time.Time, error)

DateParse Parse Date use PHP time format.

func Debug

func Debug(v ...interface{})

Debug logs a message at debug level. Deprecated: use github.com/goasana/asana/logs instead.

func Emergency

func Emergency(v ...interface{})

Emergency logs a message at emergency level. Deprecated: use github.com/goasana/asana/logs instead.

func Error

func Error(v ...interface{})

Error logs a message at error level. Deprecated: use github.com/goasana/asana/logs instead.

func ExceptMethodAppend

func ExceptMethodAppend(action string)

ExceptMethodAppend to append a slice's value into "exceptMethod", for controller's methods shouldn't reflect to AutoRouter

func Exception

func Exception(errCode uint64, ctx *context.Context)

Exception Write HttpStatus with errCode and Exec error handler if exist.

func ExecuteTemplate

func ExecuteTemplate(wr io.Writer, name string, data interface{}) error

ExecuteTemplate applies the template with name to the specified data object, writing the output to wr. A template will be executed safely in parallel.

func ExecuteViewPathTemplate

func ExecuteViewPathTemplate(wr io.Writer, name string, viewPath string, data interface{}) error

ExecuteViewPathTemplate applies the template with name and from specific viewPath to the specified data object, writing the output to wr. A template will be executed safely in parallel.

func GetConfig

func GetConfig(returnType, key string, defaultVal interface{}) (value interface{}, err error)

GetConfig get the Appconfig

func HTML2str

func HTML2str(html string) string

HTML2str returns escaping text convert from html.

func HasTemplateExt

func HasTemplateExt(paths string) bool

HasTemplateExt return this path contains supported template extension of asana or not.

func Htmlquote

func Htmlquote(text string) string

Htmlquote returns quoted html string.

func Htmlunquote

func Htmlunquote(text string) string

Htmlunquote returns unquoted html string.

func Info

func Info(v ...interface{})

Info compatibility alias for Warning() Deprecated: use github.com/goasana/asana/logs instead.

func Informational

func Informational(v ...interface{})

Informational logs a message at info level. Deprecated: use github.com/goasana/asana/logs instead.

func InitAsanaBeforeTest

func InitAsanaBeforeTest(appConfigPath string)

InitAsanaBeforeTest is for test package init

func LoadAppConfig

func LoadAppConfig(source source.Source) error

LoadAppConfig allow developer to apply a config

func LogAccess

func LogAccess(ctx *context.Context, startTime *time.Time, statusCode int)

LogAccess logging info HTTP Access

func MapGet

func MapGet(arg1 interface{}, arg2 ...interface{}) (interface{}, error)

MapGet getting value from map by keys usage:

data["m"] = M{
    "a": 1,
    "1": map[string]float64{
        "c": 4,
    },
}

{{ map_get m "a" }} // return 1 {{ map_get m 1 "c" }} // return 4

func NotNil

func NotNil(a interface{}) (isNil bool)

NotNil the same as CompareNot

func Notice

func Notice(v ...interface{})

Notice logs a message at notice level. Deprecated: use github.com/goasana/asana/logs instead.

func ParseForm

func ParseForm(form url.Values, obj interface{}) error

ParseForm will parse form values to struct via tag.

func Policy

func Policy(pattern, method string, policy ...PolicyFunc)

Policy Register new policy in asana

func RenderForm

func RenderForm(obj interface{}) template.HTML

RenderForm will render object to form html. obj must be a struct pointer.

func Run

func Run(params ...string)

Run asana application. asana.Run() default run on HttpPort asana.Run("localhost") asana.Run(":8089") asana.Run("127.0.0.1:8089")

func RunWithMiddleWares

func RunWithMiddleWares(addr string, mws ...MiddleWare)

RunWithMiddleWares Run asana application with middlewares.

func SetLevel

func SetLevel(l int)

SetLevel sets the global log level used by the simple logger. Deprecated: use github.com/goasana/asana/logs instead.

func SetLogFuncCall

func SetLogFuncCall(b bool)

SetLogFuncCall set the CallDepth, default is 3 Deprecated: use github.com/goasana/asana/logs instead.

func SetLogger

func SetLogger(adapterName string, config string) error

SetLogger sets a new logger. Deprecated: use github.com/goasana/asana/logs instead.

func SetTemplateFSFunc

func SetTemplateFSFunc(fnt templateFSFunc)

SetTemplateFSFunc set default filesystem function

func Str2html

func Str2html(raw string) template.HTML

Str2html Convert string to template.HTML type.

func Substr

func Substr(s string, start, length int) string

Substr returns the substr from start to length.

func TestAsanaInit

func TestAsanaInit(ap string)

TestAsanaInit is for test package init

func Trace

func Trace(v ...interface{})

Trace logs a message at trace level. compatibility alias for Warning() Deprecated: use github.com/goasana/asana/logs instead.

func URLFor

func URLFor(endpoint string, values ...interface{}) string

URLFor returns url string with another registered controller handler with params.

	usage:

	URLFor(".index")
	print URLFor("index")
 router /login
	print URLFor("login")
	print URLFor("login", "next","/"")
 router /profile/:username
	print UrlFor("profile", ":username","John Doe")
	result:
	/
	/login
	/login?next=/
	/user/John Doe

 more detail http://asana.me/docs/mvc/controller/urlbuilding.md

func Walk

func Walk(fs http.FileSystem, root string, walkFn filepath.WalkFunc) error

Walk walks the file tree rooted at root in filesystem, calling walkFn for each file or directory in the tree, including root. All errors that arise visiting files and directories are filtered by walkFn.

func Warn

func Warn(v ...interface{})

Warn compatibility alias for Warning() Deprecated: use github.com/goasana/asana/logs instead.

func Warning

func Warning(v ...interface{})

Warning logs a message at warning level. Deprecated: use github.com/goasana/asana/logs instead.

Types

type App

type App struct {
	Handlers *ControllerRegister
	Server   *http.Server
}

App defines asana application with a new PatternServeMux.

var (
	// AsanaApp is an application instance
	AsanaApp *App
)

func AddTemplateEngine

func AddTemplateEngine(extension string, fn templatePreProcessor) *App

AddTemplateEngine add a new templatePreProcessor which support extension

func Any

func Any(rootPath string, f FilterFunc) *App

Any used to register router for all methods usage:

asana.Any("/api", func(ctx *context.Context){
      ctx.Body("hello world")
})

func AutoPrefix

func AutoPrefix(prefix string, c ControllerInterface) *App

AutoPrefix adds controller handler to AsanaApp with prefix. it's same to App.AutoRouterWithPrefix. if asana.AutoPrefix("/admin",&MainContorlller{}) and MainController has methods List and Page, visit the url /admin/main/list to exec List function or /admin/main/page to exec Page function.

func AutoRouter

func AutoRouter(c ControllerInterface) *App

AutoRouter adds defined controller handler to AsanaApp. it's same to App.AutoRouter. if asana.AddAuto(&MainContorlller{}) and MainController has methods List and Page, visit the url /main/list to exec List function or /main/page to exec Page function.

func DelStaticPath

func DelStaticPath(url string) *App

DelStaticPath removes the static folder setting in this url pattern in asana application.

func Delete

func Delete(rootPath string, f FilterFunc) *App

Delete used to register router for Delete method usage:

asana.Delete("/api", func(ctx *context.Context){
      ctx.Body("hello world")
})

func ErrorController

func ErrorController(c ControllerInterface) *App

ErrorController registers ControllerInterface to each http err code string. usage:

asana.ErrorController(&controllers.ErrorController{})

func ErrorHandler

func ErrorHandler(code string, h http.HandlerFunc) *App

ErrorHandler registers http.HandlerFunc to each http err code string. usage:

asana.ErrorHandler("404",NotFound)
asana.ErrorHandler("500",InternalServerError)

func Get

func Get(rootPath string, f FilterFunc) *App

Get used to register router for Get method usage:

asana.Get("/", func(ctx *context.Context){
      ctx.Body("hello world")
})

func Handler

func Handler(rootPath string, h http.Handler, options ...interface{}) *App

Handler used to register a Handler router usage:

asana.Handler("/api", http.HandlerFunc(func (w http.ResponseWriter, r *http.HTTPRequest) {
      fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
}))
func Head(rootPath string, f FilterFunc) *App

Head used to register router for Head method usage:

asana.Head("/api", func(ctx *context.Context){
      ctx.Body("hello world")
})

func Include

func Include(cList ...ControllerInterface) *App

Include will generate router file in the router/xxx.go from the controller's comments usage: asana.Include(&BankAccount{}, &OrderController{},&RefundController{},&ReceiptController{})

type BankAccount struct{
  asana.Controller
}

register the function

func (b *BankAccount)Mapping(){
 b.Mapping("ShowAccount" , b.ShowAccount)
 b.Mapping("ModifyAccount", b.ModifyAccount)
}

//@router /account/:id [get]

func (b *BankAccount) ShowAccount(){
   //logic
}

//@router /account/:id [post]

func (b *BankAccount) ModifyAccount(){
   //logic
}

the comments @router url methodlist url support all the function Router's pattern methodlist [get post head put delete options *]

func InsertFilter

func InsertFilter(pattern string, pos int, filter FilterFunc, params ...bool) *App

InsertFilter adds a FilterFunc with pattern condition and action constant. The pos means action constant including asana.BeforeStatic, asana.BeforeRouter, asana.BeforeExec, asana.AfterExec and asana.FinishRouter. The bool params is for setting the returnOnOutput value (false allows multiple filters to execute)

func NewApp

func NewApp() *App

NewApp returns a new asana application.

func Options

func Options(rootPath string, f FilterFunc) *App

Options used to register router for Options method usage:

asana.Options("/api", func(ctx *context.Context){
      ctx.Body("hello world")
})

func Patch

func Patch(rootPath string, f FilterFunc) *App

Patch used to register router for Patch method usage:

asana.Patch("/api", func(ctx *context.Context){
      ctx.Body("hello world")
})

func Post

func Post(rootPath string, f FilterFunc) *App

Post used to register router for Post method usage:

asana.Post("/api", func(ctx *context.Context){
      ctx.Body("hello world")
})

func Put

func Put(rootPath string, f FilterFunc) *App

Put used to register router for Put method usage:

asana.Put("/api", func(ctx *context.Context){
      ctx.Body("hello world")
})

func RESTRouter

func RESTRouter(rootPath string, c ControllerInterface) *App

RESTRouter adds a restful controller handler to AsanaApp. its' controller implements asana.ControllerInterface and defines a param "pattern/:objectId" to visit each resource.

func Router

func Router(rootPath string, c ControllerInterface, mappingMethods ...string) *App

Router adds a patterned controller handler to AsanaApp. it's an alias method of App.Router. usage:

simple router
asana.Router("/admin", &admin.UserController{})
asana.Router("/admin/index", &admin.ArticleController{})

regex router

asana.Router("/api/:id([0-9] )", &controllers.RController{})

custom rules
asana.Router("/api/list",&RestController{},"*:ListFood")
asana.Router("/api/create",&RestController{},"post:CreateFood")
asana.Router("/api/update",&RestController{},"put:UpdateFood")
asana.Router("/api/delete",&RestController{},"delete:DeleteFood")

func SetStaticPath

func SetStaticPath(url string, path string) *App

SetStaticPath sets static directory path and proper url pattern in asana application. if asana.SetStaticPath("static","public"), visit /static/* to load static file in folder "public".

func SetViewsPath

func SetViewsPath(path string) *App

SetViewsPath sets view directory path in asana application.

func UnregisterFixedRoute

func UnregisterFixedRoute(fixedRoute string, method string) *App

UnregisterFixedRoute unregisters the route with the specified fixedRoute. It is particularly useful in web applications that inherit most routes from a base webapp via the underscore import, and aim to overwrite only certain paths. The method parameter can be empty or "*" for all HTTP methods, or a particular method type (e.g. "GET" or "POST") for selective removal.

Usage (replace "GET" with "*" for all methods):

asana.UnregisterFixedRoute("/yourpreviouspath", "GET")
asana.Router("/yourpreviouspath", yourControllerAddress, "get:GetNewPage")

func (*App) Run

func (app *App) Run(mws ...MiddleWare)

Run asana application.

type Config

type Config struct {
	AppName             string //Application name
	RunMode             string //Running Mode: dev | prod
	RouterCaseSensitive bool
	ServerName          string
	RecoverPanic        bool
	RecoverFunc         func(*context.Context)
	CopyRequestBody     bool
	EnableGzip          bool
	MaxMemory           int64
	EnableErrorsShow    bool
	EnableErrorsRender  bool
	Listen              Listen
	WebConfig           WebConfig
	Log                 LogConfig
}

Config is the main struct for BConfig

type Controller

type Controller struct {
	// context data
	*context.Context

	AppController interface{}

	// template data
	TplName        string
	ViewPath       string
	Layout         string
	LayoutSections map[string]string // the key is the section name and the value is the template name
	TplPrefix      string
	TplExt         string
	EnableRender   bool
	// contains filtered or unexported fields
}

Controller defines some basic http request handler operations, such as http context, template and view, session and xsrf.

func (*Controller) CustomAbort

func (c *Controller) CustomAbort(status int, body string)

CustomAbort stops controller handler and show the error data, it's similar Aborts, but support status code and body.

func (*Controller) Delete

func (c *Controller) Delete()

Delete adds a request function to handle DELETE request.

func (*Controller) DestroySession

func (c *Controller) DestroySession()

DestroySession cleans session data and session cookie.

func (*Controller) Finish

func (c *Controller) Finish()

Finish runs after request function execution.

func (*Controller) Get

func (c *Controller) Get()

Get adds a request function to handle GET request.

func (*Controller) GetXSRFToken

func (c *Controller) GetXSRFToken() string

GetXSRFToken creates a CSRF token string and returns.

func (*Controller) HandlerFunc

func (c *Controller) HandlerFunc(fnName string) bool

HandlerFunc call function with the name

func (*Controller) Head

func (c *Controller) Head()

Head adds a request function to handle HEAD request.

func (*Controller) Init

func (c *Controller) Init(ctx *context.Context, controllerName, actionName string, app interface{})

Init generates default values of controller operations.

func (*Controller) Mapping

func (c *Controller) Mapping(method string, fn func())

Mapping the method to function

func (*Controller) Options

func (c *Controller) Options()

Options adds a request function to handle OPTIONS request.

func (*Controller) ParseBody

func (c *Controller) ParseBody(obj interface{}) error

ParseBody input data map to obj struct depending on the type of content.

func (*Controller) ParseForm

func (c *Controller) ParseForm(obj interface{}) error

ParseForm maps input data map to obj struct.

func (*Controller) Patch

func (c *Controller) Patch()

Patch adds a request function to handle PATCH request.

func (*Controller) Post

func (c *Controller) Post()

Post adds a request function to handle POST request.

func (*Controller) Prepare

func (c *Controller) Prepare()

Prepare runs after Init before request function execution.

func (*Controller) Put

func (c *Controller) Put()

Put adds a request function to handle PUT request.

func (*Controller) Redirect

func (c *Controller) Redirect(url string) error

Redirect sends the redirection response to url with status code.

func (*Controller) Render

func (c *Controller) Render() error

Render sends the response with rendered template bytes as text/html type.

func (*Controller) RenderBytes

func (c *Controller) RenderBytes() ([]byte, error)

RenderBytes returns the bytes of rendered template string. Do not send out response.

func (*Controller) RenderString

func (c *Controller) RenderString() (string, error)

RenderString returns the rendered template string. Do not send out response.

func (*Controller) SessionRegenerateID

func (c *Controller) SessionRegenerateID()

SessionRegenerateID regenerates session id for this session. the session data have no changes.

func (*Controller) StopRun

func (c *Controller) StopRun()

StopRun makes panic of USERSTOPRUN error and go to recover function if defined.

func (*Controller) Trace

func (c *Controller) Trace()

Trace adds a request function to handle Trace request. this method SHOULD NOT be overridden. https://tools.ietf.org/html/rfc7231#section-4.3.8 The TRACE method requests a remote, application-level loop-back of the request message. The final recipient of the request SHOULD reflect the message received, excluding some fields described below, back to the client as the message body of a 200 (OK) response with a Content-Type of "message/http" (Section 8.3.1 of [RFC7230]).

func (*Controller) URLFor

func (c *Controller) URLFor(endpoint string, values ...interface{}) string

URLFor does another controller handler in this request function. it goes to this controller method if endpoint is not clear.

func (*Controller) URLMapping

func (c *Controller) URLMapping()

URLMapping register the internal Controller router.

type ControllerComments

type ControllerComments struct {
	Method           string
	Router           string
	Filters          []*ControllerFilter
	ImportComments   []*ControllerImportComments
	FilterComments   []*ControllerFilterComments
	AllowHTTPMethods []string
	Params           []map[string]string
	MethodParams     []*param.MethodParam
}

ControllerComments store the comment for the controller method

type ControllerCommentsSlice

type ControllerCommentsSlice []ControllerComments

ControllerCommentsSlice implements the sort interface

func (ControllerCommentsSlice) Len

func (p ControllerCommentsSlice) Len() int

func (ControllerCommentsSlice) Less

func (p ControllerCommentsSlice) Less(i, j int) bool

func (ControllerCommentsSlice) Swap

func (p ControllerCommentsSlice) Swap(i, j int)

type ControllerFilter

type ControllerFilter struct {
	Pattern        string
	Pos            int
	Filter         FilterFunc
	ReturnOnOutput bool
	ResetParams    bool
}

ControllerFilter store the filter for controller

type ControllerFilterComments

type ControllerFilterComments struct {
	Pattern        string
	Pos            int
	Filter         string // NOQA
	ReturnOnOutput bool
	ResetParams    bool
}

ControllerFilterComments store the comment for controller level filter

type ControllerImportComments

type ControllerImportComments struct {
	ImportPath  string
	ImportAlias string
}

ControllerImportComments store the import comment for controller needed

type ControllerInfo

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

ControllerInfo holds information about the controller.

type ControllerInterface

type ControllerInterface interface {
	Init(ct *context.Context, controllerName, actionName string, app interface{})
	Prepare()
	Get()
	Post()
	Delete()
	Put()
	Head()
	Patch()
	Options()
	Trace()
	Finish()
	Render() error
	XSRFToken() string
	CheckXSRFCookie() bool
	HandlerFunc(fn string) bool
	URLMapping()
}

ControllerInterface is an interface to uniform all controller handler.

type ControllerRegister

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

ControllerRegister containers registered router rules, controller handlers and filters.

func NewControllerRegister

func NewControllerRegister() *ControllerRegister

NewControllerRegister returns a new ControllerRegister.

func (*ControllerRegister) Add

func (p *ControllerRegister) Add(pattern string, c ControllerInterface, mappingMethods ...string)

Add controller handler and pattern rules to ControllerRegister. usage:

default methods is the same name as method
Add("/user",&UserController{})
Add("/api/list",&RestController{},"*:ListFood")
Add("/api/create",&RestController{},"post:CreateFood")
Add("/api/update",&RestController{},"put:UpdateFood")
Add("/api/delete",&RestController{},"delete:DeleteFood")
Add("/api",&RestController{},"get,post:ApiFunc"
Add("/simple",&SimpleController{},"get:GetFunc;post:PostFunc")

func (*ControllerRegister) AddAuto

AddAuto router to ControllerRegister. example asana.AddAuto(&MainContorlller{}), MainController has method List and Page. visit the url /main/list to execute List function /main/page to execute Page function.

func (*ControllerRegister) AddAutoPrefix

func (p *ControllerRegister) AddAutoPrefix(prefix string, c ControllerInterface)

AddAutoPrefix Add auto router to ControllerRegister with prefix. example asana.AddAutoPrefix("/admin",&MainContorlller{}), MainController has method List and Page. visit the url /admin/main/list to execute List function /admin/main/page to execute Page function.

func (*ControllerRegister) AddMethod

func (p *ControllerRegister) AddMethod(method, pattern string, f FilterFunc)

AddMethod add http method router usage:

AddMethod("get","/api/:id", func(ctx *context.Context){
      ctx.Body("hello world")
})

func (*ControllerRegister) Any

func (p *ControllerRegister) Any(pattern string, f FilterFunc)

Any add all method usage:

Any("/api/:id", func(ctx *context.Context){
      ctx.Body("hello world")
})

func (*ControllerRegister) Delete

func (p *ControllerRegister) Delete(pattern string, f FilterFunc)

Delete add delete method usage:

Delete("/api/:id", func(ctx *context.Context){
      ctx.Body("hello world")
})

func (*ControllerRegister) FindPolicy

func (p *ControllerRegister) FindPolicy(cont *context.Context) []PolicyFunc

FindPolicy Find Router info for URL

func (*ControllerRegister) FindRouter

func (p *ControllerRegister) FindRouter(context *context.Context) (routerInfo *ControllerInfo, isFind bool)

FindRouter Find Router info for URL

func (*ControllerRegister) Get

func (p *ControllerRegister) Get(pattern string, f FilterFunc)

Get add get method usage:

Get("/", func(ctx *context.Context){
      ctx.Body("hello world")
})

func (*ControllerRegister) Handler

func (p *ControllerRegister) Handler(pattern string, h http.Handler, options ...interface{})

Handler add user defined Handler

func (*ControllerRegister) Head

func (p *ControllerRegister) Head(pattern string, f FilterFunc)

Head add head method usage:

Head("/api/:id", func(ctx *context.Context){
      ctx.Body("hello world")
})

func (*ControllerRegister) Include

func (p *ControllerRegister) Include(cList ...ControllerInterface)

Include only when the Runmode is dev will generate router file in the router/auto.go from the controller Include(&BankAccount{}, &OrderController{},&RefundController{},&ReceiptController{})

func (*ControllerRegister) InsertFilter

func (p *ControllerRegister) InsertFilter(pattern string, pos int, filter FilterFunc, params ...bool) error

InsertFilter Add a FilterFunc with pattern rule and action constant. params is for:

  1. setting the returnOnOutput value (false allows multiple filters to execute)
  2. determining whether or not params need to be reset.

func (*ControllerRegister) Options

func (p *ControllerRegister) Options(pattern string, f FilterFunc)

Options add options method usage:

Options("/api/:id", func(ctx *context.Context){
      ctx.Body("hello world")
})

func (*ControllerRegister) Patch

func (p *ControllerRegister) Patch(pattern string, f FilterFunc)

Patch add patch method usage:

Patch("/api/:id", func(ctx *context.Context){
      ctx.Body("hello world")
})

func (*ControllerRegister) Post

func (p *ControllerRegister) Post(pattern string, f FilterFunc)

Post add post method usage:

Post("/api", func(ctx *context.Context){
      ctx.Body("hello world")
})

func (*ControllerRegister) Put

func (p *ControllerRegister) Put(pattern string, f FilterFunc)

Put add put method usage:

Put("/api/:id", func(ctx *context.Context){
      ctx.Body("hello world")
})

func (*ControllerRegister) ServeHTTP

func (p *ControllerRegister) ServeHTTP(rw http.ResponseWriter, r *http.Request)

Implement http.Handler interface.

func (*ControllerRegister) URLFor

func (p *ControllerRegister) URLFor(endpoint string, values ...interface{}) string

URLFor does another controller handler in this request function. it can access any controller method.

type FileSystem

type FileSystem struct {
}

FileSystem action for file operations

func (FileSystem) Open

func (d FileSystem) Open(name string) (http.File, error)

Open open a file

type FilterFunc

type FilterFunc func(*context.Context)

FilterFunc defines a filter function which is invoked before the controller handler is executed.

type FilterHandler

type FilterHandler interface {
	Filter(*context.Context) bool
}

FilterHandler is an interface for

var (
	// HTTPMETHOD list the supported http methods.
	HTTPMETHOD = map[string]bool{
		"GET":       true,
		"POST":      true,
		"PUT":       true,
		"DELETE":    true,
		"PATCH":     true,
		"OPTIONS":   true,
		"HEAD":      true,
		"TRACE":     true,
		"CONNECT":   true,
		"MKCOL":     true,
		"COPY":      true,
		"MOVE":      true,
		"PROPFIND":  true,
		"PROPPATCH": true,
		"LOCK":      true,
		"UNLOCK":    true,
	}

	// DefaultAccessLogFilter will skip the accesslog if return true
	DefaultAccessLogFilter FilterHandler = &logFilter{}
)

type FilterRouter

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

FilterRouter defines a filter operation which is invoked before the controller handler is executed. It can match the URL against a pattern, and execute a filter function when a request with a matching URL arrives.

func (*FilterRouter) ValidRouter

func (f *FilterRouter) ValidRouter(url string, ctx *context.Context) bool

ValidRouter checks if the current request is matched by this filter. If the request is matched, the values of the URL parameters defined by the filter pattern are also returned.

type FlashData

type FlashData struct {
	Data map[string]string
}

FlashData is a tools to maintain data when using across request.

func NewFlash

func NewFlash() *FlashData

NewFlash return a new empty FlashData struct.

func ReadFromRequest

func ReadFromRequest(c *Controller) *FlashData

ReadFromRequest parsed flash data from encoded values in cookie.

func (*FlashData) Error

func (fd *FlashData) Error(msg string, args ...interface{})

Error writes error message to flash.

func (*FlashData) Notice

func (fd *FlashData) Notice(msg string, args ...interface{})

Notice writes notice message to flash.

func (*FlashData) Set

func (fd *FlashData) Set(key string, msg string, args ...interface{})

Set message to flash

func (*FlashData) Store

func (fd *FlashData) Store(c *Controller)

Store does the saving operation of flash data. the data are encoded and saved in cookie.

func (*FlashData) Success

func (fd *FlashData) Success(msg string, args ...interface{})

Success writes success message to flash.

func (*FlashData) Warning

func (fd *FlashData) Warning(msg string, args ...interface{})

Warning writes warning message to flash.

type LinkNamespace

type LinkNamespace func(*Namespace)

LinkNamespace used as link action

func NSAfter

func NSAfter(filterList ...FilterFunc) LinkNamespace

NSAfter add Namespace FinishRouter filter

func NSAny

func NSAny(rootPath string, f FilterFunc) LinkNamespace

NSAny call Namespace Any

func NSAutoPrefix

func NSAutoPrefix(prefix string, c ControllerInterface) LinkNamespace

NSAutoPrefix call Namespace AutoPrefix

func NSAutoRouter

func NSAutoRouter(c ControllerInterface) LinkNamespace

NSAutoRouter call Namespace AutoRouter

func NSBefore

func NSBefore(filterList ...FilterFunc) LinkNamespace

NSBefore Namespace BeforeRouter filter

func NSCond

func NSCond(cond namespaceCond) LinkNamespace

NSCond is Namespace Condition

func NSDelete

func NSDelete(rootPath string, f FilterFunc) LinkNamespace

NSDelete call Namespace Delete

func NSGet

func NSGet(rootPath string, f FilterFunc) LinkNamespace

NSGet call Namespace Get

func NSHandler

func NSHandler(rootPath string, h http.Handler) LinkNamespace

NSHandler add handler

func NSHead

func NSHead(rootPath string, f FilterFunc) LinkNamespace

NSHead call Namespace Head

func NSInclude

func NSInclude(cList ...ControllerInterface) LinkNamespace

NSInclude Namespace Include ControllerInterface

func NSNamespace

func NSNamespace(prefix string, params ...LinkNamespace) LinkNamespace

NSNamespace add sub Namespace

func NSOptions

func NSOptions(rootPath string, f FilterFunc) LinkNamespace

NSOptions call Namespace Options

func NSPatch

func NSPatch(rootPath string, f FilterFunc) LinkNamespace

NSPatch call Namespace Patch

func NSPost

func NSPost(rootPath string, f FilterFunc) LinkNamespace

NSPost call Namespace Post

func NSPut

func NSPut(rootPath string, f FilterFunc) LinkNamespace

NSPut call Namespace Put

func NSRouter

func NSRouter(rootPath string, c ControllerInterface, mappingMethods ...string) LinkNamespace

NSRouter call Namespace Router

type Listen

type Listen struct {
	Graceful          bool // Graceful means use graceful module to start the server
	ServerTimeOut     int64
	ListenTCP4        bool
	EnableHTTP        bool
	HTTPAddr          string
	HTTPPort          int
	AutoTLS           bool
	Domains           []string
	TLSCacheDir       string
	EnableHTTPS       bool
	EnableMutualHTTPS bool
	HTTPSAddr         string
	HTTPSPort         int
	HTTPSCertFile     string
	HTTPSKeyFile      string
	TrustCaFile       string
	EnableAdmin       bool
	AdminAddr         string
	AdminPort         int
	EnableFcgi        bool
	EnableStdIo       bool // EnableStdIo works with EnableFcgi Use FCGI via standard I/O
}

Listen holds for http and https related config

type LogConfig

type LogConfig struct {
	AccessLogs       bool
	EnableStaticLogs bool   //log static files requests default: false
	AccessLogsFormat string //access log format: JSON_FORMAT, APACHE_FORMAT or empty string
	FileLineNum      bool
	Outputs          map[string]string // Store Adaptor : config
}

LogConfig holds Log related config

type M

type M map[string]interface{}

M is Map shortcut

func PrintTree

func PrintTree() M

PrintTree prints all registered routers.

type MiddleWare

type MiddleWare func(http.Handler) http.Handler

MiddleWare function for http.Handler

type Namespace

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

Namespace is store all the info

func NewNamespace

func NewNamespace(prefix string, params ...LinkNamespace) *Namespace

NewNamespace get new Namespace

func (*Namespace) Any

func (n *Namespace) Any(rootPath string, f FilterFunc) *Namespace

Any same as asana.Any refer: https://godoc.org/github.com/goasana/asana#Any

func (*Namespace) AutoPrefix

func (n *Namespace) AutoPrefix(prefix string, c ControllerInterface) *Namespace

AutoPrefix same as asana.AutoPrefix refer: https://godoc.org/github.com/goasana/asana#AutoPrefix

func (*Namespace) AutoRouter

func (n *Namespace) AutoRouter(c ControllerInterface) *Namespace

AutoRouter same as asana.AutoRouter refer: https://godoc.org/github.com/goasana/asana#AutoRouter

func (*Namespace) Cond

func (n *Namespace) Cond(cond namespaceCond) *Namespace

Cond set condition function if cond return true can run this namespace, else can't usage:

ns.Cond(func (ctx *context.Context) bool{
      if ctx.Domain() == "api.asana.me" {
        return true
      }
      return false
  })

Cond as the first filter

func (*Namespace) Delete

func (n *Namespace) Delete(rootPath string, f FilterFunc) *Namespace

Delete same as asana.Delete refer: https://godoc.org/github.com/goasana/asana#Delete

func (*Namespace) Filter

func (n *Namespace) Filter(action string, filter ...FilterFunc) *Namespace

Filter add filter in the Namespace action has before & after FilterFunc usage:

Filter("before", func (ctx *context.Context){
      _, ok := ctx.Session("uid").(int)
      if !ok && ctx.HTTPRequest.RequestURI != "/login" {
         ctx.Redirect(302, "/login")
       }
  })

func (*Namespace) Get

func (n *Namespace) Get(rootPath string, f FilterFunc) *Namespace

Get same as asana.Get refer: https://godoc.org/github.com/goasana/asana#Get

func (*Namespace) Handler

func (n *Namespace) Handler(rootPath string, h http.Handler) *Namespace

Handler same as asana.Handler refer: https://godoc.org/github.com/goasana/asana#Handler

func (*Namespace) Head

func (n *Namespace) Head(rootPath string, f FilterFunc) *Namespace

Head same as asana.Head refer: https://godoc.org/github.com/goasana/asana#Head

func (*Namespace) Include

func (n *Namespace) Include(cList ...ControllerInterface) *Namespace

Include add include class refer: https://godoc.org/github.com/goasana/asana#Include

func (*Namespace) Namespace

func (n *Namespace) Namespace(ns ...*Namespace) *Namespace

Namespace add nest Namespace usage: ns := asana.NewNamespace(“/v1”). Namespace(

asana.NewNamespace("/shop").
    Get("/:id", func(ctx *context.Context) {
        ctx.Body([]byte("shopinfo"))
}),
asana.NewNamespace("/order").
    Get("/:id", func(ctx *context.Context) {
        ctx.Body([]byte("orderinfo"))
}),
asana.NewNamespace("/crm").
    Get("/:id", func(ctx *context.Context) {
        ctx.Body([]byte("crminfo"))
}),

)

func (*Namespace) Options

func (n *Namespace) Options(rootPath string, f FilterFunc) *Namespace

Options same as asana.Options refer: https://godoc.org/github.com/goasana/asana#Options

func (*Namespace) Patch

func (n *Namespace) Patch(rootPath string, f FilterFunc) *Namespace

Patch same as asana.Patch refer: https://godoc.org/github.com/goasana/asana#Patch

func (*Namespace) Post

func (n *Namespace) Post(rootPath string, f FilterFunc) *Namespace

Post same as asana.Post refer: https://godoc.org/github.com/goasana/asana#Post

func (*Namespace) Put

func (n *Namespace) Put(rootPath string, f FilterFunc) *Namespace

Put same as asana.Put refer: https://godoc.org/github.com/goasana/asana#Put

func (*Namespace) Router

func (n *Namespace) Router(rootPath string, c ControllerInterface, mappingMethods ...string) *Namespace

Router same as asana.Rourer refer: https://godoc.org/github.com/goasana/asana#Router

type PolicyFunc

type PolicyFunc func(*context.Context)

PolicyFunc defines a policy function which is invoked before the controller handler is executed.

type SessionConfig

type SessionConfig struct {
	SessionOn                    bool
	SessionProvider              string
	SessionName                  string
	SessionGCMaxLifetime         int64
	SessionProviderConfig        string
	SessionCookieLifeTime        int
	SessionAutoSetCookie         bool
	SessionDomain                string
	SessionDisableHTTPOnly       bool // used to allow for cross domain cookies/javascript cookies.
	SessionEnableSidInHTTPHeader bool // enable store/get the sessionId into/from http headers
	SessionNameInHTTPHeader      string
	SessionEnableSidInURLQuery   bool // enable get the sessionId from Url Query params
}

SessionConfig holds session related config

type Tree

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

Tree has three elements: FixRouter/wildCard/leaves fixRouter stores Fixed Router wildCard stores params leaves store the endpoint information

func NewTree

func NewTree() *Tree

NewTree return a new Tree

func (*Tree) AddRouter

func (t *Tree) AddRouter(pattern string, runObject interface{})

AddRouter call addSeg function

func (*Tree) AddTree

func (t *Tree) AddTree(prefix string, tree *Tree)

AddTree will add tree to the exist Tree prefix should has no params

func (*Tree) Match

func (t *Tree) Match(pattern string, ctx *context.Context) (runObject interface{})

Match router to runObject & params

type WebConfig

type WebConfig struct {
	AutoRender             bool
	EnableDocs             bool
	FlashName              string
	FlashSeparator         string
	DirectoryIndex         bool
	StaticDir              map[string]string
	StaticExtensionsToGzip []string
	TemplateLeft           string
	TemplateRight          string
	ViewsPath              string
	EnableXSRF             bool
	XSRFKey                string
	XSRFExpire             int
	Session                SessionConfig
}

WebConfig holds web related config

Directories

Path Synopsis
Package cache provide a Cache interface and some implement engine Usage: import( "github.com/goasana/asana/cache" ) bm, err := cache.NewCache(cache.MemoryProvider, `{"interval":60}`) Use it like this: bm.Put("asana", 1, 10 * time.Second) bm.Get("asana") bm.IsExist("asana") bm.Delete("asana") more docs http://asana.me/docs/module/cache.md
Package cache provide a Cache interface and some implement engine Usage: import( "github.com/goasana/asana/cache" ) bm, err := cache.NewCache(cache.MemoryProvider, `{"interval":60}`) Use it like this: bm.Put("asana", 1, 10 * time.Second) bm.Get("asana") bm.IsExist("asana") bm.Delete("asana") more docs http://asana.me/docs/module/cache.md
memcache
Package memcache for cache provider depend on github.com/bradfitz/gomemcache/memcache go install github.com/bradfitz/gomemcache/memcache Usage: import( _ "github.com/goasana/asana/cache/memcache" "github.com/goasana/asana/cache" ) bm, err := cache.NewCache(cache.MemCachedProvider, `{"conn":"127.0.0.1:11211"}`) more docs http://asana.me/docs/module/cache.md
Package memcache for cache provider depend on github.com/bradfitz/gomemcache/memcache go install github.com/bradfitz/gomemcache/memcache Usage: import( _ "github.com/goasana/asana/cache/memcache" "github.com/goasana/asana/cache" ) bm, err := cache.NewCache(cache.MemCachedProvider, `{"conn":"127.0.0.1:11211"}`) more docs http://asana.me/docs/module/cache.md
redis
Package redis for cache provider depend on github.com/go-redis/redis go install github.com/go-redis/redis Usage: import( _ "github.com/goasana/asana/cache/redis" "github.com/goasana/asana/cache" ) bm, err := cache.NewCache(cache.RedisProvider, `{"conn":"127.0.0.1:11211"}`) more docs http://asana.me/docs/module/cache.md
Package redis for cache provider depend on github.com/go-redis/redis go install github.com/go-redis/redis Usage: import( _ "github.com/goasana/asana/cache/redis" "github.com/goasana/asana/cache" ) bm, err := cache.NewCache(cache.RedisProvider, `{"conn":"127.0.0.1:11211"}`) more docs http://asana.me/docs/module/cache.md
Package context provide the context utils Usage: import "github.com/goasana/asana/context" ctx := Context{HTTPRequest:req,ResponseWriter:rw} more docs http://asana.me/docs/module/md
Package context provide the context utils Usage: import "github.com/goasana/asana/context" ctx := Context{HTTPRequest:req,ResponseWriter:rw} more docs http://asana.me/docs/module/md
Package grace use to hot reload Description: http://grisha.org/blog/2019/06/03/graceful-restart-in-golang/ Usage: import( "log" "net/http" "os" "github.com/goasana/asana/grace" ) func handler(w http.ResponseWriter, r *http.HTTPRequest) { w.Write([]byte("WORLD!")) } func main() { mux := http.NewServeMux() mux.HandleFunc("/hello", handler) err := grace.ListenAndServe("localhost:8080", mux) if err != nil { log.Println(err) } log.Println("Server on 8080 stopped") os.Exit(0) }
Package grace use to hot reload Description: http://grisha.org/blog/2019/06/03/graceful-restart-in-golang/ Usage: import( "log" "net/http" "os" "github.com/goasana/asana/grace" ) func handler(w http.ResponseWriter, r *http.HTTPRequest) { w.Write([]byte("WORLD!")) } func main() { mux := http.NewServeMux() mux.HandleFunc("/hello", handler) err := grace.ListenAndServe("localhost:8080", mux) if err != nil { log.Println(err) } log.Println("Server on 8080 stopped") os.Exit(0) }
Package httplib is used as http.Client Usage: import "github.com/goasana/asana/httplib" b := httplib.Post("http://asana.me/") b.Param("username","asana") b.Param("password","123456") b.PostFile("uploadfile1", "httplib.pdf") b.PostFile("uploadfile2", "httplib.txt") str, err := b.String() if err != nil { t.Fatal(err) } fmt.Println(str) more docs http://asana.me/docs/module/httplib.md
Package httplib is used as http.Client Usage: import "github.com/goasana/asana/httplib" b := httplib.Post("http://asana.me/") b.Param("username","asana") b.Param("password","123456") b.PostFile("uploadfile1", "httplib.pdf") b.PostFile("uploadfile2", "httplib.txt") str, err := b.String() if err != nil { t.Fatal(err) } fmt.Println(str) more docs http://asana.me/docs/module/httplib.md
Package logs provide a general log interface Usage: import "github.com/goasana/asana/logs" log := NewLogger(10000) log.SetLogger("console", "") > the first params stand for how many channel Use it like this: log.Trace("trace") log.Info("info") log.Warn("warning") log.Debug("debug") log.Critical("critical") more docs http://asana.me/docs/module/logs.md
Package logs provide a general log interface Usage: import "github.com/goasana/asana/logs" log := NewLogger(10000) log.SetLogger("console", "") > the first params stand for how many channel Use it like this: log.Trace("trace") log.Info("info") log.Warn("warning") log.Debug("debug") log.Critical("critical") more docs http://asana.me/docs/module/logs.md
alils
Package alils implements the SDK(v0.5.0) of Simple Log Service(abbr.
Package alils implements the SDK(v0.5.0) of Simple Log Service(abbr.
es
Package migration enables you to generate migrations back and forth.
Package migration enables you to generate migrations back and forth.
Package orm provide ORM for MySQL/PostgreSQL/sqlite Simple Usage package main import ( "fmt" "github.com/goasasna/asana/orm" _ "github.com/go-sql-driver/mysql" // import your used driver ) // Model Struct type User struct { Id int `orm:"auto"` Name string `orm:"size(100)"` } func init() { orm.RegisterDataBase("default", "mysql", "root:root@/my_db?charset=utf8", 30) } func main() { o := orm.NewOrm() user := User{Name: "slene"} // insert id, err := o.Insert(&user) // update user.Name = "asana" num, err := o.Update(&user) // read one u := User{Id: user.Id} err = o.Read(&u) // delete num, err = o.Delete(&u) } more docs: http://asana.me/docs/mvc/model/overview.md
Package orm provide ORM for MySQL/PostgreSQL/sqlite Simple Usage package main import ( "fmt" "github.com/goasasna/asana/orm" _ "github.com/go-sql-driver/mysql" // import your used driver ) // Model Struct type User struct { Id int `orm:"auto"` Name string `orm:"size(100)"` } func init() { orm.RegisterDataBase("default", "mysql", "root:root@/my_db?charset=utf8", 30) } func main() { o := orm.NewOrm() user := User{Name: "slene"} // insert id, err := o.Insert(&user) // update user.Name = "asana" num, err := o.Update(&user) // read one u := User{Id: user.Id} err = o.Read(&u) // delete num, err = o.Delete(&u) } more docs: http://asana.me/docs/mvc/model/overview.md
plugins
apiauth
Package apiauth provides handlers to enable apiauth support.
Package apiauth provides handlers to enable apiauth support.
asanazap
Package asanazap provides handlers to enable ZAP log.
Package asanazap provides handlers to enable ZAP log.
auth
Package auth provides handlers to enable basic auth support.
Package auth provides handlers to enable basic auth support.
authz
Package authz provides handlers to enable ACL, RBAC, ABAC authorization support.
Package authz provides handlers to enable ACL, RBAC, ABAC authorization support.
cors
Package cors provides handlers to enable CORS support.
Package cors provides handlers to enable CORS support.
Package session provider Usage: import( "github.com/goasana/asana/session" ) func init() { globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid", "enableSetCookie,omitempty": true, "gclifetime":3600, "maxLifetime": 3600, "secure": false, "cookieLifeTime": 3600, "providerConfig": ""}`) go globalSessions.GC() } more docs: http://asana.me/docs/module/session.md
Package session provider Usage: import( "github.com/goasana/asana/session" ) func init() { globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid", "enableSetCookie,omitempty": true, "gclifetime":3600, "maxLifetime": 3600, "secure": false, "cookieLifeTime": 3600, "providerConfig": ""}`) go globalSessions.GC() } more docs: http://asana.me/docs/module/session.md
couchbase
Package couchbase for session provider depend on github.com/couchbaselabs/go-couchbasee go install github.com/couchbaselabs/go-couchbase Usage: import( _ "github.com/goasana/asana/session/couchbase" "github.com/goasana/asana/session" ) func init() { globalSessions, _ = session.NewManager("couchbase", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"http://host:port/, Pool, Bucket"}“) go globalSessions.GC() } more docs: http://asana.me/docs/module/session.md
Package couchbase for session provider depend on github.com/couchbaselabs/go-couchbasee go install github.com/couchbaselabs/go-couchbase Usage: import( _ "github.com/goasana/asana/session/couchbase" "github.com/goasana/asana/session" ) func init() { globalSessions, _ = session.NewManager("couchbase", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"http://host:port/, Pool, Bucket"}“) go globalSessions.GC() } more docs: http://asana.me/docs/module/session.md
ledis
Package ledis provide session Provider
Package ledis provide session Provider
memcache
Package memcache for session provider depend on github.com/bradfitz/gomemcache/memcache go install github.com/bradfitz/gomemcache/memcache Usage: import( _ "github.com/goasana/asana/session/memcache" "github.com/goasana/asana/session" ) func init() { globalSessions, _ = session.NewManager("memcache", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:11211"}“) go globalSessions.GC() } more docs: http://asana.me/docs/module/session.md
Package memcache for session provider depend on github.com/bradfitz/gomemcache/memcache go install github.com/bradfitz/gomemcache/memcache Usage: import( _ "github.com/goasana/asana/session/memcache" "github.com/goasana/asana/session" ) func init() { globalSessions, _ = session.NewManager("memcache", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:11211"}“) go globalSessions.GC() } more docs: http://asana.me/docs/module/session.md
mysql
Package mysql for session provider depends on github.com/go-sql-driver/mysql: go install github.com/go-sql-driver/mysql mysql session support need create table as sql: CREATE TABLE `session` ( `session_key` char(64) NOT NULL, `session_data` blob, `session_expiry` int(11) unsigned NOT NULL, PRIMARY KEY (`session_key`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; Usage: import( _ "github.com/goasana/asana/session/mysql" "github.com/goasana/asana/session" ) func init() { globalSessions, _ = session.NewManager("mysql", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...&paramN=valueN]"}“) go globalSessions.GC() } more docs: http://asana.me/docs/module/session.md
Package mysql for session provider depends on github.com/go-sql-driver/mysql: go install github.com/go-sql-driver/mysql mysql session support need create table as sql: CREATE TABLE `session` ( `session_key` char(64) NOT NULL, `session_data` blob, `session_expiry` int(11) unsigned NOT NULL, PRIMARY KEY (`session_key`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; Usage: import( _ "github.com/goasana/asana/session/mysql" "github.com/goasana/asana/session" ) func init() { globalSessions, _ = session.NewManager("mysql", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...&paramN=valueN]"}“) go globalSessions.GC() } more docs: http://asana.me/docs/module/session.md
postgres
Package postgres for session provider depends on github.com/lib/pq: go install github.com/lib/pq needs this table in your database: CREATE TABLE session ( session_key char(64) NOT NULL, session_data bytea, session_expiry timestamp NOT NULL, CONSTRAINT session_key PRIMARY KEY(session_key) ); will be activated with these settings in app.conf: SessionOn = true SessionProvider = postgresql SessionSavePath = "user=a password=b dbname=c sslmode=disable" SessionName = session Usage: import( _ "github.com/goasana/asana/session/postgresql" "github.com/goasana/asana/session" ) func init() { globalSessions, _ = session.NewManager("postgresql", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"user=pqgotest dbname=pqgotest sslmode=verify-full"}“) go globalSessions.GC() } more docs: http://asana.me/docs/module/session.md
Package postgres for session provider depends on github.com/lib/pq: go install github.com/lib/pq needs this table in your database: CREATE TABLE session ( session_key char(64) NOT NULL, session_data bytea, session_expiry timestamp NOT NULL, CONSTRAINT session_key PRIMARY KEY(session_key) ); will be activated with these settings in app.conf: SessionOn = true SessionProvider = postgresql SessionSavePath = "user=a password=b dbname=c sslmode=disable" SessionName = session Usage: import( _ "github.com/goasana/asana/session/postgresql" "github.com/goasana/asana/session" ) func init() { globalSessions, _ = session.NewManager("postgresql", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"user=pqgotest dbname=pqgotest sslmode=verify-full"}“) go globalSessions.GC() } more docs: http://asana.me/docs/module/session.md
redis
Package redis for session provider depend on github.com/gomodule/redigo/redis go install github.com/gomodule/redigo/redis Usage: import( _ "github.com/goasana/asana/session/redis" "github.com/goasana/asana/session" ) func init() { globalSessions, _ = session.NewManager("redis", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:7070"}“) go globalSessions.GC() } more docs: http://asana.me/docs/module/session.md
Package redis for session provider depend on github.com/gomodule/redigo/redis go install github.com/gomodule/redigo/redis Usage: import( _ "github.com/goasana/asana/session/redis" "github.com/goasana/asana/session" ) func init() { globalSessions, _ = session.NewManager("redis", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:7070"}“) go globalSessions.GC() } more docs: http://asana.me/docs/module/session.md
rediscluster
Package rediscluster for session provider depend on github.com/go-redis/redis go install github.com/go-redis/redis Usage: import( _ "github.com/goasana/asana/session/redis_cluster" "github.com/goasana/asana/session" ) func init() { globalSessions, _ = session.NewManager("redis_cluster", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:7070;127.0.0.1:7071"}“) go globalSessions.GC() } more docs: http://asana.me/docs/module/session.md
Package rediscluster for session provider depend on github.com/go-redis/redis go install github.com/go-redis/redis Usage: import( _ "github.com/goasana/asana/session/redis_cluster" "github.com/goasana/asana/session" ) func init() { globalSessions, _ = session.NewManager("redis_cluster", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:7070;127.0.0.1:7071"}“) go globalSessions.GC() } more docs: http://asana.me/docs/module/session.md
redissentinel
Package redissentinel for session provider depend on github.com/go-redis/redis go install github.com/go-redis/redis Usage: import( _ "github.com/goasana/asana/session/redis_sentinel" "github.com/goasana/asana/session" ) func init() { globalSessions, _ = session.NewManager("redis_sentinel", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:26379;127.0.0.2:26379"}“) go globalSessions.GC() } more detail about params: please check the notes on the function SessionInit in this package
Package redissentinel for session provider depend on github.com/go-redis/redis go install github.com/go-redis/redis Usage: import( _ "github.com/goasana/asana/session/redis_sentinel" "github.com/goasana/asana/session" ) func init() { globalSessions, _ = session.NewManager("redis_sentinel", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:26379;127.0.0.2:26379"}“) go globalSessions.GC() } more detail about params: please check the notes on the function SessionInit in this package
Package swagger struct definition
Package swagger struct definition
Package toolbox healthcheck type DatabaseCheck struct { } func (dc *DatabaseCheck) Check() error { if dc.isConnected() { return nil } else { return errors.New("can't connect database") } } AddHealthCheck("database",&DatabaseCheck{}) more docs: http://asana.me/docs/module/toolbox.md
Package toolbox healthcheck type DatabaseCheck struct { } func (dc *DatabaseCheck) Check() error { if dc.isConnected() { return nil } else { return errors.New("can't connect database") } } AddHealthCheck("database",&DatabaseCheck{}) more docs: http://asana.me/docs/module/toolbox.md
captcha
Package captcha implements generation and verification of image CAPTCHAs.
Package captcha implements generation and verification of image CAPTCHAs.
pagination
Package pagination provides utilities to setup a paginator within the context of a http request.
Package pagination provides utilities to setup a paginator within the context of a http request.
Package validation for validations import ( "github.com/goasana/asana/validation" "log" ) type User struct { Name string Age int } func main() { u := User{"man", 40} valid := validation.Validation{} valid.Required(u.Name, "name") valid.MaxSize(u.Name, 15, "nameMax") valid.Range(u.Age, 0, 140, "age") if valid.HasErrors() { // validation does not pass // print invalid message for _, err := range valid.Errors { log.Println(err.Key, err.Message) } } // or use like this if v := valid.Max(u.Age, 140, "ageMax"); !v.Ok { log.Println(v.Error.Key, v.Error.Message) } } more info: http://asana.me/docs/mvc/controller/validation.md
Package validation for validations import ( "github.com/goasana/asana/validation" "log" ) type User struct { Name string Age int } func main() { u := User{"man", 40} valid := validation.Validation{} valid.Required(u.Name, "name") valid.MaxSize(u.Name, 15, "nameMax") valid.Range(u.Age, 0, 140, "age") if valid.HasErrors() { // validation does not pass // print invalid message for _, err := range valid.Errors { log.Println(err.Key, err.Message) } } // or use like this if v := valid.Max(u.Age, 140, "ageMax"); !v.Ok { log.Println(v.Error.Key, v.Error.Message) } } more info: http://asana.me/docs/mvc/controller/validation.md

Jump to

Keyboard shortcuts

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