fwncs

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2021 License: MIT Imports: 43 Imported by: 7

README

N-CreativeSystem Framework

Golang original framework

Inspired by Gin + Echo.

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 NewRelicAppKey = "newrelicApp"
View Source
const PackageName = "github.com/n-creativesystem/fwncs"
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 CreateChildSpan added in v0.0.2

func CreateChildSpan(ctx context.Context, name string) opentracing.Span

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 InstrumentHandlerCounter

func InstrumentHandlerCounter(c Context)

func InstrumentHandlerDuration

func InstrumentHandlerDuration(c Context)

func InstrumentHandlerInFlight

func InstrumentHandlerInFlight(c Context)

func InstrumentHandlerResponseSize

func InstrumentHandlerResponseSize(c Context)

func MethodNotAllowed

func MethodNotAllowed() http.Handler

func NameOfFunction added in v0.0.2

func NameOfFunction(f interface{}) string

func NewHandlerWrap

func NewHandlerWrap(h interface{}) http.Handler

func NewJaegertracing added in v0.0.2

func NewJaegertracing() (io.Closer, error)

func NotFound

func NotFound() http.Handler

func RequestIDTransport added in v0.0.2

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

func TransactionNameGenerator added in v0.0.2

func TransactionNameGenerator(router *Router) map[string]map[string]TransactionInfo

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() httprouter.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
	*/
	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)

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

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

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 ElasticOption added in v0.0.2

type ElasticOption func(*elasticMiddleware)

func WithRequestIgnorer added in v0.0.2

func WithRequestIgnorer(r apmhttp.RequestIgnorerFunc) ElasticOption

func WithTracer added in v0.0.2

func WithTracer(t *apm.Tracer) ElasticOption

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 OpentracingOption added in v0.0.2

type OpentracingOption func(*opentracingOptions)

func OpentracingSpanObserver added in v0.0.2

func OpentracingSpanObserver(f func(span opentracing.Span, r *http.Request)) OpentracingOption

type Options

type Options func(builder *Builder)

func LoggerOptions added in v0.0.2

func LoggerOptions(log ILogger) Options

func UseElasticAPM added in v0.0.2

func UseElasticAPM(opts ...ElasticOption) Options

func UseNewrelic added in v0.0.2

func UseNewrelic(app *newrelic.Application) Options

func UseOpentracing added in v0.0.2

func UseOpentracing(tracer opentracing.Tracer, opts ...OpentracingOption) Options

func UsePrometheus added in v0.0.2

func UsePrometheus() Options

func (Options) Apply

func (o Options) Apply(builder *Builder)

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 {
	Router *httprouter.Router
	// 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) 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(path string, root 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 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 TraceHandler added in v0.0.2

type TraceHandler func(method, path string, h httprouter.Handle) (string, string, httprouter.Handle)
var DefaultTracing TraceHandler = func(method, path string, h httprouter.Handle) (string, string, httprouter.Handle) {
	return method, path, func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		h(w, r, p)
	}
}

func Elastic

func Elastic(r *Router, opts ...ElasticOption) TraceHandler

func JaegerMiddleware added in v0.0.2

func JaegerMiddleware(router *Router, tr opentracing.Tracer, options ...OpentracingOption) TraceHandler

func Newrelic

func Newrelic(r *Router, app *newrelic.Application) TraceHandler

type TransactionInfo added in v0.0.2

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

func (*TransactionInfo) Name added in v0.0.2

func (t *TransactionInfo) Name() string

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