flygo

package module
v0.3.3-beta2 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2020 License: Apache-2.0 Imports: 16 Imported by: 5

README

flygo

Introduction

A simple and lightweight web framework, pure native and no third dependencies.

Features

  • Pure native
  • No third dependencies
  • Support variables route
  • Support env variables for deploymenting
  • Support filter & interceptor
  • Field preset & validation
  • Session supports
  • Session listener supports
  • Go/Template supports

New

  • Support Middleware

    • logger : Built in Logger
    • cors : A Cors middleware for flygo
    • redisauth : A simple authentication with redis middleware for flygo
    • redistoken : A simple authorization with redis middleware for flygo
    • uploadfile : A upload file middleware for flygo
    • downfile : A download file middleware for flygo
  • Session Provider

Install

  1. GOPATH
mkdir -p $GOPATH/src/gitee.com/billcoding/flygo

cd $GOPATH/src/gitee.com/billcoding

git clone https://gitee.com/billcoding/flygo.git flygo
  1. Go mod
require gitee.com/billcoding/flygo TAG

Versions

https://gitee.com/billcoding/flygo/releases

Usage

package main

import (
	"gitee.com/billcoding/flygo"
)

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

	app.Get("/", func(context Context) {
		context.Text("index")
	})

	app.Run()
}

Configuration

Name Key Config Default Description
WebRoot global.webRoot app.SetWebRoot(WEB_ROOT) ./ The app webroot
StaticEnable static.enable app.SetStaticEnable(STATIC_ENABLE) false Static resource enable
StaticPattern static.pattern app.SetStaticPattern(STATIC_PATTERN) /static Static resource request URL
StaticPrefix static.prefix app.SetStaticPrefix(STATIC_PREFIX) static Static resource local file prefix
StaticCache static.cache app.SetStaticCache(STATIC_CACHE) true Static resource enable cache
ViewPrefix view.prefix app.SetViewPrefix(VIEW_PREFIX) templates View local file prefix
ViewSuffix view.suffix app.SetViewSuffix(VIEW_SUFFIX) html View local file suffix
ViewCache view.cache app.SetViewCache(VIEW_CACHE) true View enable cache
ValidateErrCode validate.err.code app.SetValidateErrCode(Validate_ERR_CODE) 1 Route field validate err code

Environment Variables

Name Description
FLYGO_HOST bind address
FLYGO_PORT bind port
FLYGO_WEB_ROOT app webroot
FLYGO_STATIC_CACHE app enable static resource cache
FLYGO_VIEW_CACHE app view cache

Middleware

  • Middleware (based on route)

    Must implements flygo.Middleware interface

app.Use(middlewares ...Middleware)
  • FilterMiddleware (based on filter)

    Must implements flygo.FilterMiddleware interface

app.UseFilter(filtermiddlewares ...FilterMiddleware)
  • InterceptorMiddleware (based on interceptor)

    Must implements flygo.InterceptorMiddleware interface

app.UseInterceptor(interceptorMiddlewares ...InterceptorMiddleware)

Default Handler Config

  • Not found resource
 app.DefaultHandler(HANDLER)
  • Not supported request
app.RequestNotSupportedHandler(HANDLER)
  • Favicon ico handler
app.FaviconIco()

The favicon ico file should be stored at $WEB_ROOT/$STATIC_PREFIX/favicon.ico

Route Types

  • Pattern route
/index/id
  • Variables route
/index/{id}/{name}

Handler Methods

  • All
app.Req(PATTERN, HANDLER, FIELD...)
  • GET
app.Get(PATTERN, HANDLER, FIELD...)
  • POST
app.Post(PATTERN, HANDLER, FIELD...)
  • DELETE
app.Delete(PATTERN, HANDLER, FIELD...)
  • PUT
app.Put(PATTERN, HANDLER, FIELD...)
  • PATCH
app.Patch(PATTERN, HANDLER, FIELD...)

Filter Config

  • Before filter
app.BeforeFilter(PATTERN, HANDLER)
  • After filter
app.AfterFilter(PATTERN, HANDLER)

Interceptor Config

  • Get prev results
context.Response.GetData()
  • Before interceptor
app.BeforeInterceptor(PATTERN, HANDLER)
  • After interceptor
app.AfterInterceptor(PATTERN, HANDLER)

Field Preset

  • First set part enable
field.Preset()
  • Default value
field.DefaultVal(DEFAULT_VAL)
  • Concat multiple values
field.Concat(true)
  • Concat rune
field.ConcatRune(CONCAT_RUNE)
  • Split single value
field.Split(true)
  • Split rune
field.SplitRune(SPLIT_RUNE)

Field Validation

  • First set part enable
field.Validate()
  • Min number value
field.Min(MIN_VALUE)
  • Max number value
field.Max(MAX_VALUE)
  • Min length string
field.MinLength(MIN_LENGTH)
  • Max length string
field.MaxLength(MAX_LENGTH)
  • Optional values
field.Enums(VALUE...)
  • Regex validation
field.Regex(PATTERN)

Global Cache

  • Set data
app.SetCache(KEY,DATA)
  • Get data
app.GetCache(KEY)
  • Remove data
app.RemoveCache(KEY)
  • Clear caches
app.ClearCaches()

Multipart Support

  • First parse the request
context.ParseMultipart(MEMORY_SIZE)
  • Get a multipart file
context.GetMultipartFile(FILE_NAME)
  • Get some multipart files
context.GetMultipartFiles(FILE_NAME)
  • Get multipart file original filename
multipartFile.Filename()
  • Get multipart file size in byte
multipartFile.Size()
  • Get multipart file MIME type
multipartFile.ContentType()
  • Get formdata request header
multipartFile.Header(NAME)
  • Get formdata request all headers
multipartFile.Headers()
  • Copy to local disk
multipartFile.Copy(DISK_PATH)

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Logger = &logger{}

Functions

This section is empty.

Types

type App

type App struct {
	SessionConfig *SessionConfig //Session Config
	// contains filtered or unexported fields
}

Define app struct

func GetApp

func GetApp() *App

Return app

func NewApp

func NewApp() *App

Return new App

func (*App) AfterFilter

func (a *App) AfterFilter(pattern string, filterHandler FilterHandler) *App

Route after filter

func (*App) AfterInterceptor

func (a *App) AfterInterceptor(pattern string, interceptorHandler InterceptorHandler) *App

Route after interceptor

func (*App) Banner

func (a *App) Banner(banner bool) *App

Enable banner print

func (*App) BeforeFilter

func (a *App) BeforeFilter(pattern string, filterHandler FilterHandler) *App

Route before filter

func (*App) BeforeInterceptor

func (a *App) BeforeInterceptor(pattern string, interceptorHandler InterceptorHandler) *App

Route before interceptor

func (*App) ClearCaches

func (a *App) ClearCaches()

clear caches

func (*App) DefaultHandler

func (a *App) DefaultHandler(handler Handler) *App

Config default handler

func (*App) Delete

func (a *App) Delete(pattern string, handler Handler, fields ...*Field) *App

Route Handler for DELETE method

func (*App) FaviconIco

func (a *App) FaviconIco() *App

Enable default favicon ico handler

func (*App) Get

func (a *App) Get(pattern string, handler Handler, fields ...*Field) *App

Route Handler for GET method

func (*App) GetAllCaches

func (a *App) GetAllCaches() map[string]interface{}

get all caches

func (*App) GetCache

func (a *App) GetCache(key string) interface{}

Get data from app storage

func (*App) GetContextPath

func (a *App) GetContextPath() string

Get contextPath

func (*App) GetSessionEnable

func (a *App) GetSessionEnable() bool

Get session enable

func (*App) GetStaticCache

func (a *App) GetStaticCache() bool

Get static cache

func (*App) GetStaticEnable

func (a *App) GetStaticEnable() bool

Get static enable

func (*App) GetStaticPattern

func (a *App) GetStaticPattern() string

Get static pattern

func (*App) GetStaticPrefix

func (a *App) GetStaticPrefix() string

Get static prefix

func (*App) GetTemplateDelimLeft

func (a *App) GetTemplateDelimLeft() string

Get Template delims left

func (*App) GetTemplateDelimRight

func (a *App) GetTemplateDelimRight() string

Get Template delims right

func (*App) GetTemplateEnable

func (a *App) GetTemplateEnable() bool

Get Template enable

func (*App) GetTemplateFuncs

func (a *App) GetTemplateFuncs() template.FuncMap

Get Template funcs

func (*App) GetValidateErrCode

func (a *App) GetValidateErrCode() int

Get validate err code

func (*App) GetViewCache

func (a *App) GetViewCache() bool

Get view cache

func (*App) GetViewEnable

func (a *App) GetViewEnable() bool

Get view enable

func (*App) GetViewPrefix

func (a *App) GetViewPrefix() string

Get view prefix

func (*App) GetViewSuffix

func (a *App) GetViewSuffix() string

Get view suffix

func (*App) GetWebRoot

func (a *App) GetWebRoot() string

Get webRoot

func (*App) LogFatal

func (a *App) LogFatal(message string, args ...interface{})

Log fatal

func (*App) LogInfo

func (a *App) LogInfo(message string, args ...interface{})

Log info

func (*App) LogWarn

func (a *App) LogWarn(message string, args ...interface{})

Log warn

func (*App) Patch

func (a *App) Patch(pattern string, handler Handler, fields ...*Field) *App

Route Handler for PATCH method

func (*App) Post

func (a *App) Post(pattern string, handler Handler, fields ...*Field) *App

Route Handler for POST method

func (*App) PreflightedHandler

func (a *App) PreflightedHandler(handler Handler) *App

Config preflighted handler

func (*App) Put

func (a *App) Put(pattern string, handler Handler, fields ...*Field) *App

Route Handler for PUT method

func (*App) RegisterStaticRes

func (a *App) RegisterStaticRes(fileExt, contentType string) *App

Register a static res

func (*App) RemoveCache

func (a *App) RemoveCache(key string)

remove data from app storage

func (*App) Req

func (a *App) Req(pattern string, handler Handler, fields ...*Field) *App

Route Handler for all method

func (*App) RequestNotSupportedHandler

func (a *App) RequestNotSupportedHandler(handler Handler) *App

Config request not supported handler

func (*App) Run

func (a *App) Run()

Run the server

func (*App) RunAs

func (a *App) RunAs(host string, port int)

Run as the server

func (*App) SessionEnable

func (a *App) SessionEnable(sessionEnable bool) *App

Enable sessions

func (*App) SessionProvider

func (a *App) SessionProvider(sessionProvider SessionProvider) *App

Get app session provider

func (*App) Sessions

func (a *App) Sessions() map[string]Session

Get sessions

func (*App) SetCache

func (a *App) SetCache(key string, data interface{})

Set data into app storage

func (*App) SetContextPath

func (a *App) SetContextPath(contextPath string) *App

Set contextPath

func (*App) SetSessionEnable

func (a *App) SetSessionEnable(enable bool) *App

Set session enable

func (*App) SetStaticCache

func (a *App) SetStaticCache(cache bool) *App

Set static cache

func (*App) SetStaticEnable

func (a *App) SetStaticEnable(enable bool) *App

Set static enable

func (*App) SetStaticPattern

func (a *App) SetStaticPattern(pattern string) *App

Set static pattern

func (*App) SetStaticPrefix

func (a *App) SetStaticPrefix(prefix string) *App

Set static prefix

func (*App) SetTemplateDelimLeft

func (a *App) SetTemplateDelimLeft(left string) *App

Set Template delims left

func (*App) SetTemplateDelimRight

func (a *App) SetTemplateDelimRight(right string) *App

Set Template delims right

func (*App) SetTemplateEnable

func (a *App) SetTemplateEnable(enable bool) *App

Set Template enable

func (*App) SetTemplateFuncs

func (a *App) SetTemplateFuncs(funcMap template.FuncMap) *App

Set Template funcs

func (*App) SetValidateErrCode

func (a *App) SetValidateErrCode(code int) *App

Set validate err code

func (*App) SetViewCache

func (a *App) SetViewCache(cache bool) *App

Set view cache

func (*App) SetViewEnable

func (a *App) SetViewEnable(enable bool) *App

Set view enable

func (*App) SetViewPrefix

func (a *App) SetViewPrefix(prefix string) *App

Set view prefix

func (*App) SetViewSuffix

func (a *App) SetViewSuffix(suffix string) *App

Set view suffix

func (*App) SetWebRoot

func (a *App) SetWebRoot(webRoot string) *App

Set webRoot

func (*App) TLS

func (a *App) TLS(certFile, keyFile string)

Enable TLS mode

func (*App) Use

func (a *App) Use(middlewares ...Middleware) *App

Using middlewares

func (*App) UseFilter

func (a *App) UseFilter(filterMiddlewares ...FilterMiddleware) *App

Using filter middlewares

func (*App) UseFilterWithConfig

func (a *App) UseFilterWithConfig(fmwConfig FilterMiddlewareConfig, filterMiddleware FilterMiddleware) *App

Using filter middlewares with config

func (*App) UseInterceptor

func (a *App) UseInterceptor(interceptorMiddlewares ...InterceptorMiddleware) *App

Using interceptor middlewares

func (*App) UseInterceptorWithConfig

func (a *App) UseInterceptorWithConfig(imwConfig InterceptorMiddlewareConfig, interceptorMiddleware InterceptorMiddleware) *App

Using interceptor middlewares with config

func (*App) UseWithConfig

func (a *App) UseWithConfig(mwConfig MiddlewareConfig, middleware Middleware) *App

Using middlewares with config

type Context

type Context struct {
	Request          *http.Request               //request
	RequestURI       string                      //request uri
	ParsedRequestURI string                      //parsed request uri
	RequestMethod    string                      //request method
	RequestHeader    http.Header                 //request header
	ResponseWriter   http.ResponseWriter         //Response writer
	ResponseHeader   *http.Header                //Response header
	Multipart        map[string][]*MultipartFile //multipart map
	Parameters       map[string][]string         //map[string][]string
	MultipartParsed  bool                        //multipart parsed ?
	Response         *Response                   //Response

	Cookies   map[string]*http.Cookie //cookies
	SessionId string                  //session id
	Session   Session                 //session
	// contains filtered or unexported fields
}

Define Context struct

func (*Context) AddHeader

func (c *Context) AddHeader(name, value string) *Context

Add Response header

func (*Context) AddViewFuncMap

func (c *Context) AddViewFuncMap(name string, fn interface{}) *Context

Add view funcMap

func (*Context) Binary

func (c *Context) Binary(buffer []byte)

Response binary to client

func (*Context) BinaryWith

func (c *Context) BinaryWith(buffer []byte, contentType string)

Response binary to client with ContentType

func (*Context) ClearCaches

func (c *Context) ClearCaches()

Clear app cache

func (*Context) ClearMiddlewareCtx

func (c *Context) ClearMiddlewareCtx(name string)

Clear middleware c

func (*Context) GetCache

func (c *Context) GetCache(key string) interface{}

Get app cache

func (*Context) GetMiddlewareCtx

func (c *Context) GetMiddlewareCtx(name string) map[string]interface{}

Get middleware c

func (*Context) GetMiddlewareData

func (c *Context) GetMiddlewareData(name, key string) interface{}

Get middleware data

func (*Context) GetMultipartFile

func (c *Context) GetMultipartFile(name string) *MultipartFile

Get multipart file

func (*Context) GetMultipartFiles

func (c *Context) GetMultipartFiles(name string) []*MultipartFile

Get request parameter

func (*Context) GetParameter

func (c *Context) GetParameter(name string) string

Get request parameter

func (*Context) GetParameterWithDefault

func (c *Context) GetParameterWithDefault(name, defaultValue string) string

Get request parameter with default

func (*Context) GetParameters

func (c *Context) GetParameters(name string) []string

Get request parameters

func (*Context) GetParametersWithDefault

func (c *Context) GetParametersWithDefault(name string, defaultValue []string) []string

Get request parameters with default

func (*Context) Image

func (c *Context) Image(buffer []byte)

Response image to client

func (*Context) JSON

func (c *Context) JSON(data interface{})

Response json to client

func (*Context) ParseMultipart

func (c *Context) ParseMultipart(maxMemory int64) error

Parse Multipart

func (*Context) RemoveCache

func (c *Context) RemoveCache(key string)

Remove app cache

func (*Context) RemoveMiddlewareData

func (c *Context) RemoveMiddlewareData(name, key string)

Remove middleware data

func (*Context) SetCache

func (c *Context) SetCache(key string, data interface{})

Set app cache

func (*Context) SetDone

func (c *Context) SetDone(done bool) *Context

Set done

func (*Context) SetHeader

func (c *Context) SetHeader(name, value string) *Context

Set content type

func (*Context) SetMiddlewareData

func (c *Context) SetMiddlewareData(name, key string, val interface{})

Set middleware data

func (*Context) SetViewFuncMap

func (c *Context) SetViewFuncMap(funcMap template.FuncMap) *Context

Set view funcMap

func (*Context) Text

func (c *Context) Text(text string)

Response text to client

func (*Context) View

func (c *Context) View(name string)

Response view to client

func (*Context) ViewWithData

func (c *Context) ViewWithData(name string, data map[string]interface{})

Response view to client with data

type Field

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

Define field struct

func NewField

func NewField(name string) *Field

func (*Field) Concat

func (field *Field) Concat(concat bool) *Field

concat

func (*Field) ConcatRune

func (field *Field) ConcatRune(concatRune rune) *Field

concat rune

func (*Field) DefaultVal

func (field *Field) DefaultVal(defaultVal string) *Field

default val

func (*Field) Enums

func (field *Field) Enums(enums ...string) *Field

enums

func (*Field) Fixed

func (field *Field) Fixed(fixed string) *Field

fixed

func (*Field) Length

func (field *Field) Length(length int) *Field

length

func (*Field) Max

func (field *Field) Max(max int) *Field

max

func (*Field) MaxLength

func (field *Field) MaxLength(maxLength int) *Field

maxLength

func (*Field) Min

func (field *Field) Min(min int) *Field

min

func (*Field) MinLength

func (field *Field) MinLength(minLength int) *Field

minLength

func (*Field) Name

func (field *Field) Name(name string) *Field

name

func (*Field) Preset

func (field *Field) Preset(preset bool) *Field

set

func (*Field) Regex

func (field *Field) Regex(regex string) *Field

regex

func (*Field) Split

func (field *Field) Split(split bool) *Field

split

func (*Field) SplitRune

func (field *Field) SplitRune(splitRune rune) *Field

split rune

func (*Field) Validate

func (field *Field) Validate(validate bool) *Field

validate

type FilterContext

type FilterContext struct {
	RequestURI       string
	ParsedRequestURI string
	RequestMethod    string
	RequestHeader    http.Header
	ResponseHeader   *http.Header
	Parameters       map[string][]string
	// contains filtered or unexported fields
}

Define FilterContext struct

func (*FilterContext) ClearCaches

func (c *FilterContext) ClearCaches()

Clear app cache

func (*FilterContext) ClearMiddlewareCtx

func (c *FilterContext) ClearMiddlewareCtx(name string)

Clear middleware c

func (*FilterContext) GetCache

func (c *FilterContext) GetCache(key string) interface{}

Get app cache

func (*FilterContext) GetMiddlewareCtx

func (c *FilterContext) GetMiddlewareCtx(name string) map[string]interface{}

Get middleware ctx

func (*FilterContext) GetMiddlewareData

func (c *FilterContext) GetMiddlewareData(name, key string) interface{}

Get middleware data

func (*FilterContext) RemoveCache

func (c *FilterContext) RemoveCache(key string)

Remove app cache

func (*FilterContext) RemoveMiddlewareData

func (c *FilterContext) RemoveMiddlewareData(name, key string)

Remove middleware data

func (*FilterContext) SetCache

func (c *FilterContext) SetCache(key string, data interface{})

Set app cache

func (*FilterContext) SetMiddlewareData

func (c *FilterContext) SetMiddlewareData(name, key string, val interface{})

Set middleware data

type FilterHandler

type FilterHandler func(*FilterContext)

Define filter handler

type FilterMiddleware

type FilterMiddleware interface {
	//Set FilterMiddleware name
	Name() string
	//Set FilterMiddleware type
	Type() string
	//Set FilterMiddleware pattern
	Pattern() string
	//Process FilterMiddleware
	Process() FilterHandler
}

Define Filter Middleware interface

type FilterMiddlewareConfig

type FilterMiddlewareConfig struct {
	Name    string
	Type    string
	Pattern string
}

Define FilterMiddlewareConfig struct

type Handler

type Handler func(*Context)

Define handler

type InterceptorHandler

type InterceptorHandler func(*Context)

Define interceptor handler

type InterceptorMiddleware

type InterceptorMiddleware interface {
	//Set InterceptorMiddleware name
	Name() string
	//Set InterceptorMiddleware type
	Type() string
	//Set InterceptorMiddleware pattern
	Pattern() string
	//Process InterceptorMiddleware
	Process() InterceptorHandler
}

Define Interceptor Middleware interface

type InterceptorMiddlewareConfig

type InterceptorMiddlewareConfig struct {
	Name    string
	Type    string
	Pattern string
}

Define InterceptorMiddlewareConfig struct

type Middleware

type Middleware interface {
	//Set Middleware name
	Name() string
	//Set Middleware method
	Method() string
	//Set Middleware pattern
	Pattern() string
	//Process Middleware
	Process() Handler
	//Set Middleware fields
	Fields() []*Field
}

Define Middleware interface

type MiddlewareConfig

type MiddlewareConfig struct {
	Name    string
	Method  string
	Pattern string
	Fields  []*Field
}

Define MiddlewareConfig struct

type MultipartFile

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

Define MultipartFile struct

func (*MultipartFile) ContentType

func (file *MultipartFile) ContentType() string

Get multipart file content type

func (*MultipartFile) Copy

func (file *MultipartFile) Copy(distName string) error

Copy file to dist name

func (*MultipartFile) Filename

func (file *MultipartFile) Filename() string

Get multipart file name

func (*MultipartFile) Header

func (file *MultipartFile) Header(name string) string

Get multipart header

func (*MultipartFile) Headers

func (file *MultipartFile) Headers() map[string][]string

Get multipart headers

func (*MultipartFile) Size

func (file *MultipartFile) Size() int64

Get multipart file size in byte

type Response

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

Define Response struct

func (*Response) GetContentType

func (response *Response) GetContentType() string

Get content type

func (*Response) GetData

func (response *Response) GetData() []byte

Get data

func (*Response) SetContentType

func (response *Response) SetContentType(contentType string) *Response

Set content type

func (*Response) SetDone

func (response *Response) SetDone(done bool) *Response

Set done

type Session

type Session interface {
	Id() string                                     //Get session Id
	SetExpiresTime(lifeTime time.Duration)          //Set expires time
	Get(name string) interface{}                    //Get data
	GetAll() map[string]interface{}                 //Get all data
	Set(name string, val interface{})               //Set data
	SetAll(data map[string]interface{}, flush bool) //Set all data
	Del(name string)                                //Del by name
	Clear()                                         //Clear all data
}

Define Session interface

type SessionConfig

type SessionConfig struct {
	Timeout           time.Duration   //session idle timeout
	CreatedListener   sessionListener //SessionCreatedListener
	DestoryedListener sessionListener //SessionDestoryedListener
	RefreshedListener sessionListener //SessionRefreshedListener
}

Define SessionConfig struct

type SessionCreatedListener

type SessionCreatedListener sessionListener

call when the session be created

type SessionDestoryedListener

type SessionDestoryedListener sessionListener

call when the session be destoryed

type SessionProvider

type SessionProvider interface {
	Exists(id string) bool                          //Get session is exists
	GetId(r *http.Request) string                   //Get SessionId from client
	Del(id string)                                  //Del Session from provider
	Get(id string) Session                          //Get Session from provider
	GetAll() map[string]Session                     //Get All Session from provider
	New(config *SessionConfig) Session              //Get new Session from provider
	Clear()                                         //Clear all sessions
	Refresh(session Session, config *SessionConfig) //Refresh handler from provider
}

Define SessionProvider interface

type SessionRefreshedListener

type SessionRefreshedListener sessionListener

call when the session be refreshed

type StaticHandler

type StaticHandler func(c *Context, contentType, resourcePath string)

Define static handler

Jump to

Keyboard shortcuts

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