literoute

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2019 License: GPL-3.0 Imports: 26 Imported by: 0

README

Lite Route

One lite http Route For GoLang. It supports:

  • URL Parameters
  • Party (Sub Route)
  • Http Middleware
  • Customize Http Status Code
  • Customize Body Encoder and Decoder
  • Route Parameters Validators
  • Lite and Fast
  • No dependency libs
Example

Install

go get -u github.com/pharosnet/literoute

New Mux

mux := literoute.New(Config{
		BodyEncoder: JsonBodyEncode,
		Status: CustomizeStatus{
			Succeed:        200,
			Fail:           555,
			NotFound:       444,
			InvalidRequest: 440,
		},
		PostMaxMemory: DefaultPostMaxMemory,
	})

Append Middleware

type LogMid struct {}

func (m *LogMid) Handle(ctx Context) bool {
	log.Println(ctx)
	return true
}

mux.AppendMiddleware(&LogMid{})

Register Handlers

func Root(ctx Context) {
	log.Println(
		ctx.GzipResponseWriter().WriteString(
			FormatTimeRFC3339Nano(time.Now().UTC()),
		),
	)
}

type Todo struct {
	Id   string
	Name string
	Var  string
	Time time.Time
}

func TodoGet(ctx Context) {
	ctx.Fail(Todo{
		Id:   "1",
		Name: ctx.Param("name"),
		Time: time.Now(),
	})
}

func TodoVar(ctx Context) {
	ctx.Fail(Todo{
		Id:   "1",
		Name: ctx.Param("name"),
		Var:  ctx.Param("var"),
		Time: time.Now(),
	})
}

mux.Get("/", Root)

party := mux.Party("/todo")

party.Get("/:name|IsInt", TodoGet)

party.Get("/:name/:var", TodoVar)

Register Validator

type IsIntValidator struct {}

func (v *IsIntValidator) Validate(param string) bool {
	if _, err := strconv.Atoi(param); err != nil {
		return false
	}
	return true
}

func (v *IsIntValidator) OnFail(ctx Context) {
	ctx.Fail(map[string]string{
		"msg": "param is not int",
	})
}

mux.RegisterValidator("IsInt", &IsIntValidator{})

Http Listen And Serve

log.Fatalln(http.ListenAndServe(":8080", mux))
Speed
goos: windows
goarch: amd64
pkg: github.com/pharosnet/literoute
BenchmarkLiteMux-16    	10000000	       148 ns/op
PASS

Documentation

Index

Constants

View Source
const (
	ContentTypeHeaderKey            = "Content-Type"
	LastModifiedHeaderKey           = "Last-Modified"
	IfModifiedSinceHeaderKey        = "If-Modified-Since"
	CacheControlHeaderKey           = "Cache-Control"
	ETagHeaderKey                   = "ETag"
	ContentDispositionHeaderKey     = "Content-Disposition"
	ContentLengthHeaderKey          = "Content-Length"
	ContentEncodingHeaderKey        = "Content-Encoding"
	GzipHeaderValue                 = "gzip"
	AcceptEncodingHeaderKey         = "Accept-Encoding"
	VaryHeaderKey                   = "Vary"
	ContentBinaryHeaderValue        = "application/octet-stream"
	ContentHTMLHeaderValue          = "text/html"
	ContentJSONHeaderValue          = "application/json"
	ContentJavascriptHeaderValue    = "application/javascript"
	ContentTextHeaderValue          = "text/plain"
	ContentXMLHeaderValue           = "text/xml"
	ContentXMLUnreadableHeaderValue = "application/xml"
	ContentFormHeaderValue          = "application/x-www-form-urlencoded"
	ContentFormMultipartHeaderValue = "multipart/form-data"

	XRealIp        = "X-Real-Ip"
	CfConnectingIp = "CF-Connecting-IP"

	DefaultPostMaxMemory = 32 << 20 // 32MB
)
View Source
const (
	JsonBodyEncode = iota
	XmlBodyEncode
)
View Source
const (
	NoWritten         = -1
	StatusCodeWritten = 0
)

Variables

View Source
var (
	ErrNotFound           = errors.New("not found")
	ErrPreconditionFailed = errors.New("precondition failed")
	ErrGzipNotSupported   = errors.New("client does not support gzip compression")
)
View Source
var DefaultConfig = Config{
	BodyEncoder: JsonBodyEncode,
	Status: CustomizeStatus{
		Succeed:        200,
		Fail:           555,
		NotFound:       444,
		InvalidRequest: 440,
	},
	PostMaxMemory: DefaultPostMaxMemory,
}
View Source
var DefaultJSONOptions = JSON{}
View Source
var DefaultJSONPOptions = JSONP{}
View Source
var DefaultXMLOptions = XML{}
View Source
var ErrPushNotSupported = errors.New("push feature is not supported by this ResponseWriter")
View Source
var ParseTimeRFC3339 = func(ctx Context, text string) (t time.Time, err error) {
	t, err = time.Parse(time.RFC3339, text)
	if err != nil {
		return http.ParseTime(text)
	}

	return
}
View Source
var ParseTimeRFC3339Nano = func(ctx Context, text string) (t time.Time, err error) {
	t, err = time.Parse(time.RFC3339Nano, text)
	if err != nil {
		return http.ParseTime(text)
	}

	return
}
View Source
var Pusher = func(ctx Context) {
	ctx.Push()
}
View Source
var UnixEpochTime = time.Unix(0, 0)

Functions

func CookieCleanPath

func CookieCleanPath(c *http.Cookie)

func DecodeQuery

func DecodeQuery(path string) string

func DecodeURL

func DecodeURL(uri string) string

func FormValueDefault

func FormValueDefault(r *http.Request, name string, def string, postMaxMemory int64, resetBody bool) string

func FormatTimeRFC3339

func FormatTimeRFC3339(t time.Time) string

func FormatTimeRFC3339Nano

func FormatTimeRFC3339Nano(t time.Time) string

func GetBody

func GetBody(r *http.Request, resetBody bool) ([]byte, error)

func GetForm

func GetForm(r *http.Request, postMaxMemory int64, resetBody bool) (form map[string][]string, found bool)

func GetHost

func GetHost(r *http.Request) string

func IsZeroTime

func IsZeroTime(t time.Time) bool

func LastCapturedContextID

func LastCapturedContextID() uint64

func WriteJSON

func WriteJSON(writer io.Writer, v interface{}, options JSON) (int, error)

func WriteJSONP

func WriteJSONP(writer io.Writer, v interface{}, options JSONP) (int, error)

func WriteXML

func WriteXML(writer io.Writer, v interface{}, options XML) (int, error)

func XMLMap

func XMLMap(elementName string, v map[string]interface{}) xml.Marshaler

Types

type BodyDecoder

type BodyDecoder interface {
	Decode(data []byte) error
}

type BodyEncoder

type BodyEncoder interface {
	Encode(v interface{}) []byte
}

type Config

type Config struct {
	BodyEncoder   int
	Status        CustomizeStatus
	PostMaxMemory int64
}

type Context

type Context interface {
	Mux() *LiteMux
	Request() (r *http.Request)
	ResponseWriter() ResponseWriter
	ResetResponseWriter(ResponseWriter)
	Method() string
	Path() string
	RequestPath(escape bool) string
	Host() string
	FullRequestURI() string
	RemoteAddr(headerNames ...string) string
	GetHeader(name string) string

	IsAjax() bool

	IsMobile() bool
	Header(name string, value string) Context

	ContentType(cType string) Context
	GetContentType() string
	GetContentTypeRequested() string
	GetContentLength() int64
	StatusCode(statusCode int) Context
	GetStatusCode() int

	AbsoluteURI(s string) string

	Redirect(urlToRedirect string, statusHeader ...int)

	Param(key string) string
	ParamInt(key string) (int, error)
	ParamInt32(key string) (int32, error)
	ParamInt64(key string) (int64, error)

	URLParamExists(name string) bool
	URLParamDefault(name string, def string) string
	URLParam(name string) string
	URLParamTrim(name string) string
	URLParamEscape(name string) string
	URLParamInt(name string) (int, error)
	URLParamIntDefault(name string, def int) int
	URLParamInt32Default(name string, def int32) int32
	URLParamInt64(name string) (int64, error)
	URLParamInt64Default(name string, def int64) int64
	URLParamFloat64(name string) (float64, error)
	URLParamFloat64Default(name string, def float64) float64
	URLParamBool(name string) (bool, error)
	URLParams() map[string]string

	FormValueDefault(name string, def string) string
	FormValue(name string) string
	FormValues() map[string][]string
	PostValueDefault(name string, def string) string
	PostValue(name string) string
	PostValueTrim(name string) string
	PostValueInt(name string) (int, error)
	PostValueIntDefault(name string, def int) int
	PostValueInt64(name string) (int64, error)
	PostValueInt64Default(name string, def int64) int64
	PostValueFloat64(name string) (float64, error)
	PostValueFloat64Default(name string, def float64) float64
	PostValueBool(name string) (bool, error)
	PostValues(name string) []string
	FormFile(key string) (multipart.File, *multipart.FileHeader, error)
	UploadFormFiles(destDirectory string, before ...func(Context, *multipart.FileHeader)) (n int64, err error)

	Succeed(v interface{})
	NotFound()
	Fail(v interface{})
	Invalid(v interface{})

	SetMaxRequestBodySize(limitOverBytes int64)

	GetBody() ([]byte, error)

	UnmarshalBody(outPtr interface{}, unMarshaller Unmarshaller) error
	ReadJSON(jsonObjectPtr interface{}) error

	ReadForm(formObject interface{}) error

	ReadQuery(ptr interface{}) error

	Write(body []byte) (int, error)

	WriteString(body string) (int, error)

	SetLastModified(modifyTime time.Time)

	CheckIfModifiedSince(modifyTime time.Time) (bool, error)

	WriteNotModified()

	WriteWithExpiration(body []byte, modifyTime time.Time) (int, error)

	StreamWriter(writer func(w io.Writer) bool)

	ClientSupportsGzip() bool

	WriteGzip(b []byte) (int, error)

	TryWriteGzip(b []byte) (int, error)

	GzipResponseWriter() *GzipResponseWriter

	Gzip(enable bool)

	Binary(data []byte) (int, error)
	Text(format string, args ...interface{}) (int, error)
	HTML(format string, args ...interface{}) (int, error)
	JSON(v interface{}, options ...JSON) (int, error)
	JSONP(v interface{}, options ...JSONP) (int, error)
	XML(v interface{}, options ...XML) (int, error)

	ServeContent(content io.ReadSeeker, filename string, modifyTime time.Time, gzipCompression bool) error

	ServeFile(filename string, gzipCompression bool) error

	SendFile(filename string, destinationName string) error

	SetCookie(cookie *http.Cookie, options ...CookieOption)

	SetCookieKV(name, value string, options ...CookieOption)

	GetCookie(name string, options ...CookieOption) string

	RemoveCookie(name string, options ...CookieOption)
	VisitAllCookies(visitor func(name string, value string))

	MaxAge() int64

	Push()

	Pusher() *ResponsePusher

	IsPushing() (*ResponsePusher, bool)

	BeginRequest(w http.ResponseWriter, r *http.Request)
	End()
}

type CookieDecoder

type CookieDecoder func(cookieName string, cookieValue string, v interface{}) error

type CookieEncoder

type CookieEncoder func(cookieName string, value interface{}) (string, error)

type CookieOption

type CookieOption func(*http.Cookie)

func CookieDecode

func CookieDecode(decode CookieDecoder) CookieOption

func CookieEncode

func CookieEncode(encode CookieEncoder) CookieOption

func CookieExpires

func CookieExpires(durFromNow time.Duration) CookieOption

func CookieHTTPOnly

func CookieHTTPOnly(httpOnly bool) CookieOption

func CookiePath

func CookiePath(path string) CookieOption

type CustomizeStatus

type CustomizeStatus struct {
	Succeed        int
	Fail           int
	NotFound       int
	InvalidRequest int
}

type GzipResponseWriter

type GzipResponseWriter struct {
	ResponseWriter
	// contains filtered or unexported fields
}

func AsGzipResponseWriter

func AsGzipResponseWriter(w ResponseWriter) *GzipResponseWriter

func (*GzipResponseWriter) Disable

func (w *GzipResponseWriter) Disable()

func (*GzipResponseWriter) EndResponse

func (w *GzipResponseWriter) EndResponse()

func (*GzipResponseWriter) FlushResponse

func (w *GzipResponseWriter) FlushResponse()

func (*GzipResponseWriter) ResetBody

func (w *GzipResponseWriter) ResetBody()

func (*GzipResponseWriter) Write

func (w *GzipResponseWriter) Write(contents []byte) (int, error)

func (*GzipResponseWriter) WriteNow

func (w *GzipResponseWriter) WriteNow(contents []byte) (int, error)

func (*GzipResponseWriter) WriteString

func (w *GzipResponseWriter) WriteString(s string) (n int, err error)

func (*GzipResponseWriter) Writef

func (w *GzipResponseWriter) Writef(format string, a ...interface{}) (n int, err error)

type HandleFunc

type HandleFunc func(ctx Context)

type JSON

type JSON struct {
	StreamingJSON bool
	UnescapeHTML  bool
	Indent        string
	Prefix        string
}

type JSONP

type JSONP struct {
	Indent   string
	Callback string
}

type LiteMux

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

func Default

func Default() (mux *LiteMux)

func New

func New(config Config) (mux *LiteMux)

func (*LiteMux) AppendMiddleware

func (m *LiteMux) AppendMiddleware(mid Middleware)

func (*LiteMux) Connect

func (m *LiteMux) Connect(path string, handle HandleFunc)

func (*LiteMux) Delete

func (m *LiteMux) Delete(path string, handle HandleFunc)

func (*LiteMux) Get

func (m *LiteMux) Get(path string, handle HandleFunc)

func (*LiteMux) Head

func (m *LiteMux) Head(path string, handle HandleFunc)

func (*LiteMux) NotFound

func (m *LiteMux) NotFound(handle HandleFunc)

func (*LiteMux) Options

func (m *LiteMux) Options(path string, handle HandleFunc)

func (*LiteMux) Party

func (m *LiteMux) Party(path string) *Router

func (*LiteMux) Patch

func (m *LiteMux) Patch(path string, handle HandleFunc)

func (*LiteMux) Post

func (m *LiteMux) Post(path string, handle HandleFunc)

func (*LiteMux) Put

func (m *LiteMux) Put(path string, handle HandleFunc)

func (*LiteMux) RegisterBodyEncode

func (m *LiteMux) RegisterBodyEncode(encode BodyEncoder)

func (*LiteMux) RegisterValidator

func (m *LiteMux) RegisterValidator(name string, validator Validator)

func (*LiteMux) ServeHTTP

func (m *LiteMux) ServeHTTP(rw http.ResponseWriter, req *http.Request)

func (*LiteMux) Trace

func (m *LiteMux) Trace(path string, handle HandleFunc)

type Middleware

type Middleware interface {
	Handle(ctx Context) bool
}

type ResponsePusher

type ResponsePusher struct {
	ResponseWriter
	// contains filtered or unexported fields
}

func (*ResponsePusher) Begin

func (w *ResponsePusher) Begin(underline ResponseWriter)

func (*ResponsePusher) Body

func (w *ResponsePusher) Body() []byte

func (*ResponsePusher) ClearHeaders

func (w *ResponsePusher) ClearHeaders()

func (*ResponsePusher) Clone

func (w *ResponsePusher) Clone() ResponseWriter

func (*ResponsePusher) EndResponse

func (w *ResponsePusher) EndResponse()

func (*ResponsePusher) Flush

func (w *ResponsePusher) Flush()

func (*ResponsePusher) FlushResponse

func (w *ResponsePusher) FlushResponse()

func (*ResponsePusher) Naive

func (w *ResponsePusher) Naive() http.ResponseWriter

func (*ResponsePusher) Push

func (w *ResponsePusher) Push(target string, opts *http.PushOptions) error

func (*ResponsePusher) Reset

func (w *ResponsePusher) Reset()

func (*ResponsePusher) ResetBody

func (w *ResponsePusher) ResetBody()

func (*ResponsePusher) ResetHeaders

func (w *ResponsePusher) ResetHeaders()

func (*ResponsePusher) SetBody

func (w *ResponsePusher) SetBody(b []byte)

func (*ResponsePusher) SetBodyString

func (w *ResponsePusher) SetBodyString(s string)

func (*ResponsePusher) Write

func (w *ResponsePusher) Write(contents []byte) (int, error)

func (*ResponsePusher) WriteString

func (w *ResponsePusher) WriteString(s string) (n int, err error)

func (*ResponsePusher) WriteTo

func (w *ResponsePusher) WriteTo(res ResponseWriter)

func (*ResponsePusher) Writef

func (w *ResponsePusher) Writef(format string, a ...interface{}) (n int, err error)

type ResponseWriter

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

	Naive() http.ResponseWriter

	IsHijacked() bool

	Writef(format string, a ...interface{}) (n int, err error)

	WriteString(s string) (n int, err error)

	StatusCode() int

	Written() int

	SetWritten(int)

	SetBeforeFlush(cb func())
	GetBeforeFlush() func()
	FlushResponse()

	BeginResponse(underline http.ResponseWriter)
	EndResponse()

	Clone() ResponseWriter

	WriteTo(ResponseWriter)

	Flusher() (http.Flusher, bool)

	CloseNotifier() (http.CloseNotifier, bool)
}

type Router

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

func (*Router) Connect

func (r *Router) Connect(path string, handle HandleFunc)

func (*Router) Delete

func (r *Router) Delete(path string, handle HandleFunc)

func (*Router) Get

func (r *Router) Get(path string, handle HandleFunc)

func (*Router) Head

func (r *Router) Head(path string, handle HandleFunc)

func (*Router) Options

func (r *Router) Options(path string, handle HandleFunc)

func (*Router) Patch

func (r *Router) Patch(path string, handle HandleFunc)

func (*Router) Post

func (r *Router) Post(path string, handle HandleFunc)

func (*Router) Put

func (r *Router) Put(path string, handle HandleFunc)

func (*Router) Trace

func (r *Router) Trace(path string, handle HandleFunc)

type UnMarshallerFunc

type UnMarshallerFunc func(data []byte, outPtr interface{}) error

func (UnMarshallerFunc) Unmarshal

func (u UnMarshallerFunc) Unmarshal(data []byte, v interface{}) error

type Unmarshaller

type Unmarshaller interface {
	Unmarshal(data []byte, outPtr interface{}) error
}

type Validator

type Validator interface {
	Validate(string) bool
	OnFail(Context)
}

type XML

type XML struct {
	Indent string
	Prefix string
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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