fwncs

package module
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2021 License: MIT Imports: 33 Imported by: 7

README

N-CreativeSystem Framework

Golang original framework

Inspired by Gin + Echo.

Content

Example

package main

import (
    "github.com/n-creativesystem/go-fwncs"
)

func main() {
    router := fwncs.Default()
    router.GET("/", func(c fwncs.Context) {})
    api := router.Group("/api/v1")
    {
        api.GET("/resource/:name", func(c fwncs.Context) {})
        api.GET("= /resource/full-match", func(c fwncs.Context) {})
    }
    router.Run(8080) // or router.RunTLS(8443, "server.crt", "server.key")
}

Documentation

Index

Constants

View Source
const (
	Uppercase    = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	Lowercase    = "abcdefghijklmnopqrstuvwxyz"
	Alphabetic   = Uppercase + Lowercase
	Numeric      = "0123456789"
	Alphanumeric = Alphabetic + Numeric
)
View Source
const (
	AuthKey = "auth_key"
)
View Source
const FormatTemplate = "time:${time_millisec}\tid:${id}\tremote_ip:${remote_ip}\thost:${host}\tmethod:${method}\turi:${uri}\tuser_agent:${user_agent}\t" +
	"status:${status}\terror:${error}\tlatency:${latency}\tlatency_human:${latency_human}\tbytes_in:${bytes_in}\tbytes_out:${bytes_out}"
View Source
const StatusCodeContextCanceled = 499

Variables

View Source
var (
	ErrEmptyAuthorization  = errors.New("token_required")
	ErrInvalidTokenRequest = errors.New("invalid_request")
	ErrInvalidToken        = errors.New("invalid_token")
)
View Source
var (
	Version  = ""
	Revision = ""
)
View Source
var DefaultLoggerConfig = LoggerConfig{
	Format:           FormatTemplate,
	CustomTimeFormat: FormatMillisec.String(),
}
View Source
var MinMaxError = errors.New("Min cannot be greater than max.")

Functions

func FromHeader added in v0.0.2

func FromHeader(schema string) func(r *http.Request) (string, error)

func FromRequestID added in v0.0.2

func FromRequestID(ctx context.Context) string

func NameOfFunction added in v0.0.2

func NameOfFunction(f interface{}) string

func NewHandlerWrap

func NewHandlerWrap(h interface{}) http.Handler

func RequestIDTransport added in v0.0.2

func RequestIDTransport(c context.Context, tr http.RoundTripper) http.RoundTripper

Types

type AuthOption added in v0.0.2

type AuthOption struct {
	Issuer        string
	Audiences     []string
	ClientID      string
	EnableOptions bool
	Extractor     TokenExtractorFunc
	KeyFunc       KeyFunc
	Schema        string
}

type Builder

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

type Cache added in v0.0.2

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

func NewCache added in v0.0.2

func NewCache() *Cache

func (*Cache) Get added in v0.0.2

func (c *Cache) Get(key string) interface{}

func (*Cache) Put added in v0.0.2

func (c *Cache) Put(key string, value interface{}, expires int64)

type Choice added in v0.0.3

type Choice struct {
	Weight float64
	Item   interface{}
}

type Choices added in v0.0.3

type Choices []Choice

func (Choices) Get added in v0.0.3

func (c Choices) Get(n int) []Choice

func (Choices) GetOne added in v0.0.3

func (c Choices) GetOne() Choice

type Context

type Context interface {
	Writer() ResponseWriter
	SetWriter(w ResponseWriter)
	GetStatus() int
	SetStatus(status int)
	ResponseSize() int
	SetHeader(key, value string)

	/*
		Request
	*/
	Request() *http.Request
	SetRequest(r *http.Request)
	Header() http.Header
	GetContext() context.Context
	SetContext(ctx context.Context)
	IsWebSocket() bool
	Scheme() string

	/*
		Abort or error
	*/
	AbortWithStatus(status int)
	AbortWithStatusAndErrorMessage(status int, err error)
	AbortWithStatusAndMessage(status int, v interface{})
	Error(err error)
	GetError() []error
	// Skip is 後続の処理を止める
	IsSkip() bool
	Skip()

	/*
		Query or URL parameter
	*/
	Param(name string) string
	Params() Params
	QueryParam(name string) string
	DefaultQuery(name string, defaultValue string) string

	/*
		Request body
	*/
	ReadJsonBody(v interface{}) error
	FormValue(name string) string
	FormFile(name string) (*multipart.FileHeader, error)
	MultiPartForm() (*multipart.Form, error)

	/*
		Cookie
	*/
	SetCookie(cookie *http.Cookie)
	Cookie(name string) (*http.Cookie, error)
	Cookies() []*http.Cookie

	/*
		Response body
	*/
	Render(status int, r render.Render)
	String(status int, format string, v ...interface{})
	JSON(status int, v interface{})
	JSONP(status int, v interface{})
	IndentJSON(status int, v interface{}, indent string)
	AsciiJSON(status int, v interface{})
	YAML(status int, v interface{})
	Template(status int, v interface{}, filenames ...string)
	TemplateText(status int, text string, v interface{})

	/*
		Middlewere or handler
	*/
	Next()
	HandlerName() string
	Logger() ILogger
	ClientIP() string
	Set(key string, value interface{})
	Get(key string) interface{}
	Redirect(status int, url string)
	GetRequestID() string

	/*
		Utils
	*/
	// HttpClient when the tr is nil, the default transport is http.DefaultTransport
	HttpClient(tr http.RoundTripper) *http.Client
	Path() string
	RealPath() string
	Method() string
	RealMethod() string
}

type DefaultResponseBody

type DefaultResponseBody struct {
	Code     int    `json:"code"`
	Status   string `json:"status"`
	Message  string `json:"message"`
	Internal error  `json:"-"`
}

func NewDefaultResponseBody

func NewDefaultResponseBody(code int, message string) *DefaultResponseBody

func (*DefaultResponseBody) Error added in v0.0.2

func (d *DefaultResponseBody) Error() string

type HandlerFunc

type HandlerFunc func(Context)

func Auth added in v0.0.2

func Auth(opt AuthOption) HandlerFunc

func Logger

func Logger() HandlerFunc

func LoggerWithConfig added in v0.0.2

func LoggerWithConfig(config LoggerConfig) HandlerFunc

func Permission added in v0.0.2

func Permission(permissionClaim string, permissions ...string) HandlerFunc

func Proxy added in v0.0.2

func Proxy(balancer ProxyBalancer) HandlerFunc

func ProxyWithConfig added in v0.0.2

func ProxyWithConfig(config ProxyConfig) HandlerFunc

func Recovery

func Recovery() HandlerFunc

func RequestID added in v0.0.2

func RequestID() HandlerFunc

func RequestIDWithConfig added in v0.0.2

func RequestIDWithConfig(config RequestIDConfig) HandlerFunc

func WrapHandler

func WrapHandler(h http.Handler) HandlerFunc

type HandlerFuncChain added in v0.0.2

type HandlerFuncChain []HandlerFunc

func (HandlerFuncChain) Last added in v0.0.2

func (hc HandlerFuncChain) Last() HandlerFunc

func (HandlerFuncChain) LastIndex added in v0.0.2

func (hc HandlerFuncChain) LastIndex() int

type HandlerMiddleware

type HandlerMiddleware func(next http.Handler) http.Handler

type HandlerWrap

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

func (*HandlerWrap) ServeHTTP

func (h *HandlerWrap) ServeHTTP(w http.ResponseWriter, r *http.Request)

type ILogger

type ILogger interface {
	Debug(v ...interface{})
	Info(v ...interface{})
	Warning(v ...interface{})
	Error(v ...interface{})
	Critical(v ...interface{})
	Write(b []byte) (int, error)
	// Copy is logger copy instance
	Copy() ILogger
	// Skip is logger skip plus instance
	Skip(n int) ILogger
	ChangeFormatType(formatType LogFormatType) ILogger
}
var Log ILogger = &logger{}

func NewLogger

func NewLogger(writer io.Writer, formatType LogFormatType, timeFmtTyp LogFormatType) ILogger

type KeyFunc added in v0.0.2

type KeyFunc func(ctx context.Context, jwksURL, kid string) (interface{}, error)

type LogFormatType

type LogFormatType string
const (
	// FormatShort time:{{.Time}}\tlevel:{{.Level}}\tmessage:{{.Message}}\n
	FormatShort LogFormatType = "time:{{.Time}}\tlevel:{{.Level}}\tmessage:{{.Message}}\n"
	// FormatStandard time:{{.Time}}\tlevel:{{.Level}}\tfilename:{{.Filename}}:{{.LineNumber}}\tmessage:{{.Message}}\n
	FormatStandard LogFormatType = "time:{{.Time}}\tlevel:{{.Level}}\tfilename:{{.Filename}}:{{.LineNumber}}\tmessage:{{.Message}}\n"
	// FormatLong time:{{.Time}}\tlevel:{{.Level}}\tfilename:{{.Filename}}:{{.LineNumber}}\tfuncname:{{.Funcname}}\tmessage:{{.Message}}\n
	FormatLong LogFormatType = "time:{{.Time}}\tlevel:{{.Level}}\tfilename:{{.Filename}}:{{.LineNumber}}\tfuncname:{{.Funcname}}\tmessage:{{.Message}}\n"
	// FormatDate 2006/01/02
	FormatDate LogFormatType = "2006/01/02"
	// FormatDatetime 2006/01/02 15:04:05
	FormatDatetime LogFormatType = "2006/01/02 15:04:05"
	// FormatMillisec 2006/01/02 15:04:05.00000
	FormatMillisec LogFormatType = "2006/01/02 15:04:05.00000"
)

func ConvertLogFmt

func ConvertLogFmt(fmt string) LogFormatType

func ConvertTimeFmt

func ConvertTimeFmt(fmt string) LogFormatType

func (LogFormatType) String

func (f LogFormatType) String() string

type LogLevel

type LogLevel int
const (
	Critical LogLevel = iota
	Error
	Warn
	Info
	Debug
)

func ConvertLevel

func ConvertLevel(level string) LogLevel

func (LogLevel) String

func (l LogLevel) String() string

type LogTemplate

type LogTemplate struct {
	Time       string
	Funcname   string
	Filename   string
	Level      string
	Goroutine  string
	LineNumber string
	Message    string
}

type LoggerConfig added in v0.0.2

type LoggerConfig struct {
	Format           string
	CustomTimeFormat string
	CustomMessage    func(tag string, writer io.Writer)
	// contains filtered or unexported fields
}

type MapRouterInformations added in v0.0.5

type MapRouterInformations map[string][]RouterInfo

type Options

type Options func(builder *Builder)

func LoggerOptions added in v0.0.2

func LoggerOptions(log ILogger) Options

func (Options) Apply

func (o Options) Apply(builder *Builder)

type Param added in v0.0.6

type Param struct {
	Key   string
	Value string
}

Param is a single URL parameter, consisting of a key and a value.

type Params added in v0.0.6

type Params []Param

Params is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.

func (Params) ByName added in v0.0.6

func (ps Params) ByName(name string) (va string)

ByName returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

func (Params) Get added in v0.0.6

func (ps Params) Get(name string) (string, bool)

Get returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

func (Params) Values added in v0.0.6

func (ps Params) Values() []string

type ProxyBalancer added in v0.0.2

type ProxyBalancer interface {
	Add(target interface{}) bool
	Remove(name string) bool
	Next(c Context) *ProxyTarget
}

func NewRandomBalancer added in v0.0.2

func NewRandomBalancer(proxies []*ProxyTarget) ProxyBalancer

func NewRoundRobinBalancer added in v0.0.2

func NewRoundRobinBalancer(proxies []*ProxyTarget) ProxyBalancer

func NewStaticWeightedRoundRobinBalancer added in v0.0.3

func NewStaticWeightedRoundRobinBalancer(proxies []*WeightProxyTarget) ProxyBalancer

type ProxyConfig added in v0.0.2

type ProxyConfig struct {
	LoadBalancer   ProxyBalancer
	Rewrite        map[string]string
	RegexRewrite   map[*regexp.Regexp]string
	Transport      http.RoundTripper
	ModifyResponse func(*http.Response) error
	ContextKey     string
}

type ProxyTarget added in v0.0.2

type ProxyTarget struct {
	Name string
	URL  *url.URL
	Meta map[string]interface{}
}

type Random added in v0.0.2

type Random struct{}

func (*Random) String added in v0.0.2

func (*Random) String(length uint8) string

type RequestIDConfig added in v0.0.2

type RequestIDConfig struct {
	Generator func() string
}

type ResponseWriter added in v0.0.2

type ResponseWriter interface {
	http.ResponseWriter
	http.Hijacker
	http.Flusher

	Status() int
	Size() int
	WriteString(string) (int, error)
	Written() bool
	WriteHeaderNow()

	Pusher() http.Pusher
}

type Router added in v0.0.2

type Router struct {
	UseRawPath             bool
	UnescapePathValues     bool
	RemoveExtraSlash       bool
	RedirectFixedPath      bool
	HandleMethodNotAllowed bool
	// contains filtered or unexported fields
}

func Default

func Default(opts ...Options) *Router

func New

func New(opts ...Options) *Router

func (*Router) Any added in v0.0.2

func (r *Router) Any(path string, h ...HandlerFunc) *Router

func (*Router) DELETE added in v0.0.2

func (r *Router) DELETE(path string, h ...HandlerFunc)

func (*Router) GET added in v0.0.2

func (r *Router) GET(path string, h ...HandlerFunc)

func (*Router) Group added in v0.0.2

func (r *Router) Group(path string, middleware ...HandlerFunc) *Router

func (*Router) HEAD added in v0.0.2

func (r *Router) HEAD(path string, h ...HandlerFunc)

func (*Router) Handler added in v0.0.2

func (r *Router) Handler(method, path string, h ...HandlerFunc)

func (*Router) NoMethod added in v0.0.6

func (r *Router) NoMethod(h ...HandlerFunc) *Router

func (*Router) NotFound added in v0.0.6

func (r *Router) NotFound(h ...HandlerFunc) *Router

func (*Router) OPTIONS added in v0.0.2

func (r *Router) OPTIONS(path string, h ...HandlerFunc)

func (*Router) PATCH added in v0.0.2

func (r *Router) PATCH(path string, h ...HandlerFunc)

func (*Router) POST added in v0.0.2

func (r *Router) POST(path string, h ...HandlerFunc)

func (*Router) PUT added in v0.0.2

func (r *Router) PUT(path string, h ...HandlerFunc)

func (*Router) Run added in v0.0.2

func (r *Router) Run(port int) error

func (*Router) RunTLS added in v0.0.2

func (r *Router) RunTLS(port int, certFile, keyFile string) error

RunTLS is https

func (*Router) RunUnix added in v0.0.2

func (r *Router) RunUnix(file string) error

RunUnix is unix domain socket

When the file is empty, the default name is www.sock

func (*Router) ServeFiles added in v0.0.2

func (r *Router) ServeFiles(paths string, fs http.FileSystem)

func (*Router) ServeHTTP added in v0.0.2

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*Router) Use added in v0.0.2

func (r *Router) Use(middleware ...HandlerFunc)

type RouterInfo added in v0.0.5

type RouterInfo struct {
	Method      string
	Path        string
	HandlerName string
}

type TokenExtractorFunc added in v0.0.2

type TokenExtractorFunc func(r *http.Request) (string, error)

func FromParameter added in v0.0.2

func FromParameter(parameterName string) TokenExtractorFunc

type WeightProxyTarget added in v0.0.3

type WeightProxyTarget struct {
	Weight float64
	*ProxyTarget
}

Directories

Path Synopsis
idp

Jump to

Keyboard shortcuts

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