ltick

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2018 License: Apache-2.0 Imports: 30 Imported by: 0

README

TICK FRAMEWORK Build Status Sourcegraph

Package tick-framework help you build your Go application extremely fast.

简体中文

Feature

  • Module
  • Life Cycle
  • Dependency Injection
  • Routing

Module

  • Config
  • Logger
  • Database
  • Cache
  • Queue
  • Filesystem

Installation

To use with latest changes:

go get github.com/ltick/tick-framework

Please add -u flag to update in the future.

go get -u github.com/ltick/tick-framework

Getting Started

Loading from data sources

Documentation

Index

Constants

View Source
const (
	JSON = content.JSON
	XML  = content.XML
	XML2 = content.XML2
	HTML = content.HTML
)

TypeNegotiator returns a content type negotiation handler.

The method takes a list of response MIME types that are supported by the application. The negotiator will determine the best response MIME type to use by checking the "Accept" HTTP header. If no match is found, the first MIME type will be used.

The negotiator will set the "Content-Type" response header as the chosen MIME type. It will call routing.Context.SetDataWriter() to set the appropriate data writer that can write data in the negotiated format.

If you do not specify any supported MIME types, the negotiator will use "text/html" as the response MIME type.

Variables

View Source
var CorsAllowAll = cors.Options{
	AllowOrigins: "*",
	AllowHeaders: "*",
	AllowMethods: "*",
}

Functions

This section is empty.

Types

type Callback

type Callback interface {
	OnStartup(*Engine) error  // Execute On After All Engine Module OnStartup
	OnShutdown(*Engine) error // Execute On After All Engine Module OnShutdown
}

type Engine

type Engine struct {
	Config  *libConfig.Instance
	Utility *libUtility.Instance
	Logger  *libLogger.Instance

	Module  *module.Instance
	Context context.Context
	Servers map[string]*Server
	// contains filtered or unexported fields
}

func New

func New(executeFile string, pathPrefix string, configName string, envPrefix string, modules []*module.Module, configOptions map[string]libConfig.Option) (engine *Engine)

func NewClassic

func NewClassic(modules []*module.Module, configOptions map[string]libConfig.Option, option *Option) (engine *Engine)

func (*Engine) GetBuiltinModule

func (e *Engine) GetBuiltinModule(moduleName string) (interface{}, error)

func (*Engine) GetBuiltinModules

func (e *Engine) GetBuiltinModules() map[string]interface{}

func (*Engine) GetConfigBool

func (e *Engine) GetConfigBool(key string) bool

func (*Engine) GetConfigInt

func (e *Engine) GetConfigInt(key string) int

func (*Engine) GetConfigInt64

func (e *Engine) GetConfigInt64(key string) int64

func (*Engine) GetConfigString

func (e *Engine) GetConfigString(key string) string

func (*Engine) GetContextValue

func (e *Engine) GetContextValue(key interface{}) interface{}

func (*Engine) GetContextValueString

func (e *Engine) GetContextValueString(key string) string

func (*Engine) GetLogger

func (e *Engine) GetLogger(name string) (*libLogger.Logger, error)

func (*Engine) GetModule

func (e *Engine) GetModule(moduleName string) (interface{}, error)

func (*Engine) GetModules

func (e *Engine) GetModules() map[string]interface{}

func (*Engine) GetServer

func (e *Engine) GetServer(name string) *Server

func (*Engine) GetValue

func (e *Engine) GetValue(key string) (interface{}, error)

func (*Engine) GetValues

func (e *Engine) GetValues() map[string]interface{}

func (*Engine) InjectModule

func (e *Engine) InjectModule() error

func (*Engine) InjectModuleByName

func (e *Engine) InjectModuleByName(moduleNames ...string) error

func (*Engine) ListenAndServe

func (e *Engine) ListenAndServe()

func (*Engine) LoadCachedConfig

func (e *Engine) LoadCachedConfig(configFilePath string, cachedConfigFilePath string)

func (*Engine) LoadConfig

func (e *Engine) LoadConfig(configPath string, configName string) *Engine

func (*Engine) LoadEnv

func (e *Engine) LoadEnv(envPrefix string) *Engine

func (*Engine) LoadEnvConfigFile

func (e *Engine) LoadEnvConfigFile(envPrefix string, dotEnvFile string) *Engine

func (*Engine) LoadModuleFileConfig

func (e *Engine) LoadModuleFileConfig(moduleName string, configFile string, configProviders map[string]interface{}, configTag ...string) (err error)

func (*Engine) LoadModuleJsonConfig

func (e *Engine) LoadModuleJsonConfig(moduleName string, configData []byte, configProviders map[string]interface{}, configTag ...string) (err error)

Register As Module

func (*Engine) LoadSystemConfig

func (e *Engine) LoadSystemConfig(configFilePath string, envPrefix string, dotEnvFile string) *Engine

func (*Engine) NewClassicServer

func (e *Engine) NewClassicServer(name string, requestTimeoutHandlers ...routing.Handler) (server *Server)

func (*Engine) NewServer

func (e *Engine) NewServer(name string, port uint, gracefulStopTimeout time.Duration, requestTimeout time.Duration, requestTimeoutHandlers ...routing.Handler) (server *Server)

func (*Engine) RegisterUserModule

func (e *Engine) RegisterUserModule(moduleName string, module module.ModuleInterface, forceOverwrites ...bool) (err error)

Register As Module

func (*Engine) RegisterValue

func (e *Engine) RegisterValue(key string, value interface{}, forceOverwrites ...bool) (err error)

Register As Value

func (*Engine) ServeHTTP

func (e *Engine) ServeHTTP(res http.ResponseWriter, req *http.Request)

func (*Engine) ServerListenAndServe

func (e *Engine) ServerListenAndServe(server *Server)

func (*Engine) ServerServeHTTP

func (e *Engine) ServerServeHTTP(name string, server *Server, res http.ResponseWriter, req *http.Request)

func (*Engine) SetConfigOptions

func (e *Engine) SetConfigOptions(configOptions map[string]libConfig.Option) (err error)

func (*Engine) SetContextValue

func (e *Engine) SetContextValue(key, val interface{})

func (*Engine) SetPathPrefix

func (e *Engine) SetPathPrefix(pathPrefix string)

func (*Engine) SetServerLogFunc

func (e *Engine) SetServerLogFunc(name string, accessLogFunc access.LogWriterFunc, faultLogFunc fault.LogFunc, recoveryHandler ...fault.ConvertErrorFunc) *Engine

func (*Engine) SetServerReuqestCallback

func (e *Engine) SetServerReuqestCallback(name string, reuqestCallback RouterCallback) *Engine

func (*Engine) SetServerReuqestCors

func (e *Engine) SetServerReuqestCors(name string, corsOptions cors.Options) *Engine

func (*Engine) SetServerReuqestSlashRemover

func (e *Engine) SetServerReuqestSlashRemover(name string, status int) *Engine

func (*Engine) SetSystemLogWriter

func (e *Engine) SetSystemLogWriter(systemLogWriter io.Writer)

func (*Engine) Shutdown

func (e *Engine) Shutdown() (err error)

func (*Engine) Startup

func (e *Engine) Startup() (err error)

func (*Engine) SystemLog

func (e *Engine) SystemLog(args ...interface{})

func (*Engine) UnregisterUserModule

func (e *Engine) UnregisterUserModule(moduleNames ...string) (err error)

Unregister As Module

func (*Engine) UnregisterValue

func (e *Engine) UnregisterValue(keys ...string) (context.Context, error)

Unregister As Value

func (*Engine) UseModule

func (e *Engine) UseModule(moduleNames ...string) (err error)

func (*Engine) WithCallback

func (e *Engine) WithCallback(callback Callback) *Engine

func (*Engine) WithLoggers

func (e *Engine) WithLoggers(handlers []*LogHanlder) *Engine

func (*Engine) WithValues

func (e *Engine) WithValues(values map[string]interface{}) *Engine

type LogHanlder

type LogHanlder struct {
	Name      string
	Formatter string
	Type      string
	Filename  string
	Writer    string // the writer name of writer (stdout, stderr, discard)
	MaxLevel  libLogger.Level
}

type Option

type Option struct {
	PathPrefix string
	EnvPrefix  string
}

type RouterCallback

type RouterCallback interface {
	OnRequestStartup(*routing.Context) error
	OnRequestShutdown(*routing.Context) error
}

type Server

type Server struct {
	Port        uint
	Router      *ServerRouter
	RouteGroups map[string]*ServerRouteGroup
	// contains filtered or unexported fields
}

func (*Server) Connect

func (s *Server) Connect(host string, route string, handlers ...routing.Handler) *Server

func (*Server) Delete

func (s *Server) Delete(host string, route string, handlers ...routing.Handler) *Server

func (*Server) Get

func (s *Server) Get(host string, route string, handlers ...routing.Handler) *Server

func (*Server) GetRouteGroup

func (s *Server) GetRouteGroup(name string) *ServerRouteGroup

func (*Server) GetRouter

func (s *Server) GetRouter() *ServerRouter

func (*Server) Options

func (s *Server) Options(host string, route string, handlers ...routing.Handler) *Server

func (*Server) Patch

func (s *Server) Patch(host string, route string, handlers ...routing.Handler) *Server

func (*Server) Post

func (s *Server) Post(host string, route string, handlers ...routing.Handler) *Server

func (*Server) Proxy

func (s *Server) Proxy(host string, route string, upstream string) *Server

func (*Server) Put

func (s *Server) Put(host string, route string, handlers ...routing.Handler) *Server

func (*Server) SetLogFunc

func (s *Server) SetLogFunc(accessLogFunc access.LogWriterFunc, faultLogFunc fault.LogFunc, recoveryHandler ...fault.ConvertErrorFunc) *Server

func (*Server) SetReuqestCallback

func (s *Server) SetReuqestCallback(reuqestCallback RouterCallback) *Server

func (*Server) SetReuqestSlashRemover

func (s *Server) SetReuqestSlashRemover(status int) *Server

func (*Server) SetServerReuqestCors

func (s *Server) SetServerReuqestCors(corsOptions cors.Options) *Server

func (*Server) SystemLog

func (s *Server) SystemLog(args ...interface{})

func (*Server) Trace

func (s *Server) Trace(host string, route string, handlers ...routing.Handler) *Server

type ServerRouteGroup

type ServerRouteGroup struct {
	*routing.RouteGroup
	// contains filtered or unexported fields
}

func (*ServerRouteGroup) AddRoute

func (g *ServerRouteGroup) AddRoute(method string, path string, handlers ...routing.Handler)

func (*ServerRouteGroup) WithCallback

func (g *ServerRouteGroup) WithCallback(callback RouterCallback) *ServerRouteGroup

type ServerRouter

type ServerRouter struct {
	*routing.Router
	// contains filtered or unexported fields
}

func (*ServerRouter) AddRouteGroup

func (r *ServerRouter) AddRouteGroup(groupName string, modules []module.ModuleInterface, handlers ...routing.Handler) *ServerRouteGroup

func (*ServerRouter) AddTypeNegotiator

func (r *ServerRouter) AddTypeNegotiator(mime string, writer routing.DataWriter) *ServerRouter

func (*ServerRouter) NewFileHandler

func (r *ServerRouter) NewFileHandler(pathMap file.PathMap, opts ...file.ServerOptions) routing.Handler

The files being served are determined using the current URL path and the specified path map. For example, if the path map is {"/css": "/www/css", "/js": "/www/js"} and the current URL path "/css/main.css", the file "<working dir>/www/css/main.css" will be served. If a URL path matches multiple prefixes in the path map, the most specific prefix will take precedence. For example, if the path map contains both "/css" and "/css/img", and the URL path is "/css/img/logo.gif", then the path mapped by "/css/img" will be used.

import (
    "log"
    "github.com/ltick/tick-framework"
)

a := New("app1", "Test Application 1", &AppInitFunc{})
server := a.AddServer(8080, 30*time.Second, 3*time.Second)
server.AddRoute("/*", server.FileServer(file.PathMap{
     "/css": "/ui/dist/css",
     "/js": "/ui/dist/js",
}))

func (*ServerRouter) WithAccessLogger

func (r *ServerRouter) WithAccessLogger(loggerFunc access.LogWriterFunc) *ServerRouter

The LogWriterFunc is provided with the http.Request and LogResponseWriter objects for the request, as well as the elapsed time since the request first came through the middleware. LogWriterFunc can then do whatever logging it needs to do.

import (
    "log"
    "github.com/ltick/tick-framework"
    "net/http"
)

func myCustomLogger(req http.Context, res access.LogResponseWriter, elapsed int64) {
    // Do something with the request, response, and elapsed time data here
}
r := routing.New()
r.UseAccessLogger(AccessLogger(myCustomLogger))

func (*ServerRouter) WithCallback

func (r *ServerRouter) WithCallback(callback RouterCallback) *ServerRouter

func (*ServerRouter) WithCors

func (r *ServerRouter) WithCors(opts cors.Options) *ServerRouter

func (*ServerRouter) WithErrorHandler

func (r *ServerRouter) WithErrorHandler(logf fault.LogFunc, errorf ...fault.ConvertErrorFunc) *ServerRouter

func (*ServerRouter) WithLanguageNegotiator

func (r *ServerRouter) WithLanguageNegotiator(languages ...string) *ServerRouter

The method takes a list of languages (locale IDs) that are supported by the application. The negotiator will determine the best language to use by checking the Accept-Language request header. If no match is found, the first language will be used.

In a handler, you can access the chosen language through routing.Context like the following:

func(c *routing.Context) error {
    language := c.Get(content.Language).(string)
}

If you do not specify languages, the negotiator will set the language to be "en-US".

func (*ServerRouter) WithPanicLogger

func (r *ServerRouter) WithPanicLogger(logf fault.LogFunc) *ServerRouter

func (*ServerRouter) WithRecoveryHandler

func (r *ServerRouter) WithRecoveryHandler(logf fault.LogFunc, errorf ...fault.ConvertErrorFunc) *ServerRouter

func (*ServerRouter) WithSlashRemover

func (r *ServerRouter) WithSlashRemover(status int) *ServerRouter

The handler will redirect the browser to the new URL without the trailing slash. The status parameter should be either http.StatusMovedPermanently (301) or http.StatusFound (302), which is to be used for redirecting GET requests. For other requests, the status code will be http.StatusTemporaryRedirect (307). If the original URL has no trailing slash, the handler will do nothing. For example,

import (
    "net/http"
    "github.com/ltick/tick-framework"
)

r := routing.New()
r.AppendStartupHandler(slash.WithSlashRemover(http.StatusMovedPermanently))

Note that Remover relies on HTTP redirection to remove the trailing slashes. If you do not want redirection, please set `Router.IgnoreTrailingSlash` to be true without using Remover.

func (*ServerRouter) WithTypeNegotiator

func (r *ServerRouter) WithTypeNegotiator(formats ...string) *ServerRouter

type ServerRouterProxy

type ServerRouterProxy struct {
	Host     string
	Route    string
	Upstream string
}

func (*ServerRouterProxy) FindStringSubmatchMap

func (sp *ServerRouterProxy) FindStringSubmatchMap(s string) map[string]string

func (*ServerRouterProxy) MatchProxy

func (sp *ServerRouterProxy) MatchProxy(r *http.Request) (*url.URL, error)

type ServerRouterRoute

type ServerRouterRoute struct {
	Host     string
	Method   string
	Route    string
	Handlers []routing.Handler
}

type State

type State int8
const (
	STATE_INITIATE State = iota
	STATE_STARTUP
	STATE_SHUTDOWN
)

Jump to

Keyboard shortcuts

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