water

package module
v0.0.0-...-f2b76e9 Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2021 License: BSD-3-Clause Imports: 24 Imported by: 6

README

water

water is a micro & pluggable web framework for Go.

water is Compatible with gin route style.

Routing Policy is from Macaron. Thanks Unknwon.

Getting Started

Please use latest go.

To install water:

go get github.com/meilihao/water

The very basic usage of water:

example see engine_test.go

output(router tree):

 Raw Router Tree:
├── / [GET     : 2]
├── /help [GET     : 2]
├── /about [GET     : 2]
├── /about [POST    : 2]
├── /about [DELETE  : 2]
├── /about [PUT     : 2]
├── /about [PATCH   : 2]
├── /about [HEAD    : 2]
├── /* [OPTIONS : 1]
├── /a
│   ├── /1 [GET     : 3]
│   ├── /<id:int> [GET     : 3]
│   └── /b
│       ├──  [GET     : 4]
│       ├── /2 [GET     : 3]
│       ├── /2 [POST    : 3]
│       ├── /2 [DELETE  : 3]
│       ├── /2 [PUT     : 3]
│       ├── /2 [PATCH   : 3]
│       ├── /<id ~ 70|80> [PUT     : 3]
│       └── /* [GET     : 3]
├── /d2/<id ~ z(d*)b> [GET     : 2]
├── /d2/<id1,id2 ~ z(d*)h(u)b> [GET     : 2]
├── /c
│   ├── /<_ ~ 70|80> [PUT     : 2]
│   ├── /<_> [GET     : 2]
│   └── /*file [GET     : 2]
└── /d
    └── /*_ [GET     : 2]


 GET's Routes:
[  2] /
[  3] /a/1
[  3] /a/<id:int>
[  4] /a/b
[  3] /a/b/*
[  3] /a/b/2
[  2] /about
[  2] /c/*file
[  2] /c/<_>
[  2] /d/*_
[  2] /d2/<id ~ z(d*)b>
[  2] /d2/<id1,id2 ~ z(d*)h(u)b>
[  2] /help


 All Routes:
[GET     : 2] /
[GET     : 2] /help
[GET     : 2] /about
[POST    : 2] /about
[DELETE  : 2] /about
[PUT     : 2] /about
[PATCH   : 2] /about
[HEAD    : 2] /about
[OPTIONS : 1] /*
[GET     : 3] /a/1
[GET     : 3] /a/<id:int>
[GET     : 4] /a/b
[GET     : 3] /a/b/2
[POST    : 3] /a/b/2
[DELETE  : 3] /a/b/2
[PUT     : 3] /a/b/2
[PATCH   : 3] /a/b/2
[PUT     : 3] /a/b/<id ~ 70|80>
[GET     : 3] /a/b/*
[GET     : 2] /d2/<id ~ z(d*)b>
[GET     : 2] /d2/<id1,id2 ~ z(d*)h(u)b>
[PUT     : 2] /c/<_ ~ 70|80>
[GET     : 2] /c/<_>
[GET     : 2] /c/*file
[GET     : 2] /d/*_


 GET's Release Router Tree:
/ [  2]
├── a
│   ├── b
│   │   ├── 2 [  3]
│   │   └── * [  3]
│   ├── 1 [  3]
│   ├── b [  4]
│   └── <id:int> [  3]
├── d2
│   ├── <id ~ z(d*)b> [  2]
│   └── <id1,id2 ~ z(d*)h(u)b> [  2]
├── c
│   ├── <_> [  2]
│   └── *file [  2]
├── d
│   └── *_ [  2]
├── help [  2]
└── about [  2]

Middlewares

Middlewares allow you easily plugin/unplugin features for your water applications.

There are already some middlewares to simplify your work:

Router

  • default Any() exclude ["Head","Options"], but can reset by water.MethodAnyExclude

binding

support gin style binding.

others

  • support http.Handler, but not recommended
  • go build --tags extended, enable advanced response

Getting Help

License

This project is under BSD License.

Documentation

Index

Constants

View Source
const (
	MIMESeparator = "; "
	CharsetUTF8   = "charset=utf-8"
)
View Source
const (
	MIMEApplicationJSON            = "application/json"
	MIMEApplicationJSONCharsetUTF8 = MIMEApplicationJSON + MIMESeparator + CharsetUTF8
	MIMEApplicationXML             = "application/xml"
	MIMEApplicationXMLCharsetUTF8  = MIMEApplicationXML + MIMESeparator + CharsetUTF8
	MIMETextHTML                   = "text/html"
	MIMETextHTMLCharsetUTF8        = MIMETextHTML + MIMESeparator + CharsetUTF8
	MIMETextPlain                  = "text/plain"
	MIMETextPlainCharsetUTF8       = MIMETextPlain + MIMESeparator + CharsetUTF8
	MIMEXMLHttpRequest             = "XMLHttpRequest"
)

MIME types

View Source
const (
	HeaderCacheControl = "Cache-Control" // Requests, Responses
	HeaderContentType  = "Content-Type"  // Requests, Responses

	HeaderUserAgent      = "User-Agent"       // Requests
	HeaderXRequestedWith = "X-Requested-With" // Requests

	HeaderExpires            = "Expires"             // Responses
	HeaderContentDisposition = "Content-Disposition" // Responses

	// Common Non-Standard Response Headers
	HeaderXForwardedFor   = "X-Forwarded-For"   // Requests
	HeaderXForwardedProto = "X-Forwarded-Proto" // Requests
	HeaderXRealIP         = "X-Real-IP"         // Requests
)

HTTP Header Fields, from chrome see https://github.com/teambition/gear/blob/master/const.go

View Source
const (
	HeaderVary   = "Vary"
	HeaderOrigin = "Origin"

	// Access control
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"
)
View Source
const (
	ETagTypeNone = iota
	ETagType1
	ETagType2
)
View Source
const (
	Stable = "stable"
	Dev    = "dev"
)

all status

View Source
const (
	DEFAULT_TPL_SET_NAME = ""
)
View Source
const (
	VERSION = "2.0.0"
)

version

Variables

View Source
var (
	LogColor      = true
	LogClose      = false
	LogHttpBody   = true
	LogTimeFormat = "2006-01-02 15:04:05"
)
View Source
var (
	// DefaultCORSConfig is the default CORS middleware config.
	DefaultCORSConfig = CORSConfig{
		AllowOrigins: []string{"*"},
		AllowMethods: []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete, http.MethodHead},
	}
)
View Source
var (
	MethodAnyExclude = []string{http.MethodHead, http.MethodOptions}
)
View Source
var Status = Dev

current status

Functions

func GenerateETag

func GenerateETag(lastModified time.Time, size int64) string

GenerateETag generates an ETag based on file modification time and size from http://lxr.nginx.org/ident?_i=ngx_http_set_etag

func GenerateETag2

func GenerateETag2(lastModified time.Time, size int64, fileName string) string

GenerateETag2 generates an ETag based on file modification time, size, filename

func MethodIndex

func MethodIndex(method string) int

func SetRender

func SetRender(r Render)

Types

type CORSConfig

type CORSConfig struct {
	// AllowOrigin defines a list of origins that may access the resource.
	// Optional. Default value []string{"*"}.
	AllowOrigins []string `json:"allow_origins"`

	// AllowMethods defines a list methods allowed when accessing the resource.
	// This is used in response to a preflight request.
	// Optional. Default value DefaultCORSConfig.AllowMethods.
	AllowMethods []string `json:"allow_methods"`

	// AllowHeaders defines a list of request headers that can be used when
	// making the actual request. This in response to a preflight request.
	// Optional. Default value []string{}.
	AllowHeaders []string `json:"allow_headers"`

	// AllowCredentials indicates whether or not the response to the request
	// can be exposed when the credentials flag is true. When used as part of
	// a response to a preflight request, this indicates whether or not the
	// actual request can be made using credentials.
	// Optional. Default value false.
	AllowCredentials bool `json:"allow_credentials"`

	// ExposeHeaders defines a whitelist headers that clients are allowed to
	// access.
	// Optional. Default value []string{}.
	ExposeHeaders []string `json:"expose_headers"`

	// MaxAge indicates how long (in seconds) the results of a preflight request
	// can be cached.
	// Optional. Default value 0.
	MaxAge int `json:"max_age"`
}

CORSConfig defines the config for CORS middleware.

type Context

type Context struct {
	Environ Environ
	Params  Params

	Request *http.Request
	ResponseWriter
	// contains filtered or unexported fields
}

Context represents the context of current request of water instance. Context体现了water处理当前请求时的上下文环境 不在Context中使用"Resp ResponseWriter"的原因:Resp.Write()和Ctx.Write()的行为不一致, 因Resp.Write()不会设置ctx.written,导致在Recovery()等地方重复调用WriteHeader而报错 "http: multiple response.WriteHeader calls".

func (*Context) Abort

func (ctx *Context) Abort(code int)

func (*Context) Attachment

func (ctx *Context) Attachment(name string, modtime time.Time, content io.ReadSeeker, inline ...bool)

func (*Context) BadRequest

func (ctx *Context) BadRequest()

400

func (*Context) Bind

func (ctx *Context) Bind(obj interface{}) error

Bind use http method and ContentType to decode req

func (*Context) BindWith

func (ctx *Context) BindWith(obj interface{}, b binding.Bindinger) error

BindWith use the assigned Bindinger to decode req

func (*Context) BodyBytes

func (ctx *Context) BodyBytes() ([]byte, error)

BodyBytes returns content of request body in bytes.

func (*Context) BodyString

func (ctx *Context) BodyString() (string, error)

BodyString returns content of request body in string.

func (*Context) ContentType

func (ctx *Context) ContentType() string

ContentType returns the Content-Type header of the request.

func (*Context) Cookie

func (ctx *Context) Cookie(name string) string

func (*Context) CookieBool

func (ctx *Context) CookieBool(name string) bool

func (*Context) CookieEscape

func (ctx *Context) CookieEscape(name string) string

func (*Context) CookieFloat64

func (ctx *Context) CookieFloat64(name string) float64

func (*Context) CookieInt

func (ctx *Context) CookieInt(name string) int

func (*Context) CookieInt64

func (ctx *Context) CookieInt64(name string) int64

func (*Context) CookieUint

func (ctx *Context) CookieUint(name string) uint

func (*Context) CookieUint64

func (ctx *Context) CookieUint64(name string) uint64

func (*Context) Data

func (ctx *Context) Data(code int, contentType string, data []byte)

func (*Context) DefaultQuery

func (ctx *Context) DefaultQuery(name, defaultValue string) string

DefaultQuery returns trimmed string, but no name return default Note: It is recommended! If not, you can use "ctx.Request.FormValue". 这是推荐的做法,如果不认同,可使用ctx.Request.FormValue.

func (*Context) DefaultQueryArray

func (ctx *Context) DefaultQueryArray(name string, defaultValue []string) []string

DefaultQueryArray returns a list of results by given query name

func (*Context) DefaultQueryBool

func (ctx *Context) DefaultQueryBool(name, defaultValue string) bool

DefaultQueryBool returns bool

func (*Context) DefaultQueryFloat64

func (ctx *Context) DefaultQueryFloat64(name, defaultValue string) float64

DefaultQueryFloat64 returns float64

func (*Context) DefaultQueryInt

func (ctx *Context) DefaultQueryInt(name, defaultValue string) int

DefaultQueryInt returns int

func (*Context) DefaultQueryInt64

func (ctx *Context) DefaultQueryInt64(name, defaultValue string) int64

DefaultQueryInt64 returns int64

func (*Context) DefaultQueryMap

func (ctx *Context) DefaultQueryMap(key string, defaultValue map[string]string) map[string]string

DefaultQueryMap returns a map for a given query key.

func (*Context) DefaultQueryUint

func (ctx *Context) DefaultQueryUint(name, defaultValue string) uint

DefaultQueryUint returns uint

func (*Context) DefaultQueryUint64

func (ctx *Context) DefaultQueryUint64(name, defaultValue string) uint64

DefaultQueryUint64 returns uint64

func (*Context) Download

func (ctx *Context) Download(fpath string, inline ...bool) error

func (*Context) File

func (ctx *Context) File(filepath string)

File writes the specified file into the body stream.

func (*Context) Forbidden

func (ctx *Context) Forbidden()

403

func (*Context) FormFile

func (ctx *Context) FormFile(name string) (multipart.File, *multipart.FileHeader, error)

func (*Context) Found

func (ctx *Context) Found(uri string)

302

func (*Context) FullPath

func (ctx *Context) FullPath() string

FullPath returns a matched route full path. For not found routes returns an empty string

func (*Context) Get

func (c *Context) Get(name string) interface{}

Get returns the value for the given name if it exists, otherwise it panics.

func (*Context) GetHeader

func (ctx *Context) GetHeader(key string) string

func (*Context) GetMaybe

func (c *Context) GetMaybe(name string) (value interface{}, exists bool)

GetMaybe returns the value for the given name, ie: (value, true). If the value does not exists it returns (nil, false)

func (*Context) HTML

func (ctx *Context) HTML(code int, name string, data interface{})

HTML renders the HTML with default template set.

func (*Context) HTMLRaw

func (ctx *Context) HTMLRaw(code int, str string)

HTMLRaw not use render

func (*Context) HTMLSet

func (ctx *Context) HTMLSet(code int, setName, tplName string, data interface{})

HTMLSet renders the HTML with given template set name.

func (*Context) HandlerName

func (ctx *Context) HandlerName() string

HandlerName returns the last handler's name. For example if the handler is "_Users()", this function will return "main._Users".

func (*Context) InternalServerError

func (ctx *Context) InternalServerError()

500

func (*Context) IsAjax

func (ctx *Context) IsAjax() bool

IsAjax returns boolean of this request is generated by ajax.

func (*Context) IsWebsocket

func (ctx *Context) IsWebsocket() bool

func (*Context) JSON

func (ctx *Context) JSON(code int, v interface{}) error

func (*Context) MovedPermanently

func (ctx *Context) MovedPermanently(uri string)

301

func (*Context) Next

func (ctx *Context) Next()

func (*Context) NotFound

func (ctx *Context) NotFound()

404

func (*Context) NotModified

func (ctx *Context) NotModified()

304

func (*Context) Param

func (ctx *Context) Param(key string) string

Param returns the value of the URL param. It is a shortcut for c.Params.String(key)

router.GET("/user/<id>", func(c *water.Context) {
    // a GET request to /user/john
    id := c.Param("id") // id == "john"
})

func (*Context) ParseFormOrMultipartForm

func (ctx *Context) ParseFormOrMultipartForm()

ParseFormOrMultipartForm parses the raw query from the URL.

func (*Context) Proxy

func (ctx *Context) Proxy() []string

Proxy returns slice of proxy client ips.

func (*Context) Query

func (ctx *Context) Query(name string) string

Query returns trimmed string. Note: It is recommended! If not, you can use "ctx.Request.FormValue". 这是推荐的做法,如果不认同,可使用ctx.Request.FormValue.

func (*Context) QueryArray

func (ctx *Context) QueryArray(name string) []string

QueryArray returns a list of results by given query name

func (*Context) QueryBool

func (ctx *Context) QueryBool(name string) bool

QueryBool returns bool

func (*Context) QueryFloat64

func (ctx *Context) QueryFloat64(name string) float64

QueryFloat64 returns float64

func (*Context) QueryInt

func (ctx *Context) QueryInt(name string) int

QueryInt returns int

func (*Context) QueryInt64

func (ctx *Context) QueryInt64(name string) int64

QueryInt64 returns int64

func (*Context) QueryMap

func (ctx *Context) QueryMap(key string) map[string]string

QueryMap returns a map for a given query key. POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1 Content-Type: application/x-www-form-urlencoded names[first]=thinkerou&names[second]=tianou

func (*Context) QueryUint

func (ctx *Context) QueryUint(name string) uint

QueryUint returns uint

func (*Context) QueryUint64

func (ctx *Context) QueryUint64(name string) uint64

QueryUint64 returns uint64

func (*Context) ReadCloser

func (ctx *Context) ReadCloser() io.ReadCloser

ReadCloser returns a ReadCloser for request body, need Close()

func (*Context) RealIp

func (ctx *Context) RealIp() string

IP returns request client ip. if using proxy, return first proxy ip.

func (*Context) SaveUploadedFile

func (ctx *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error
	// Upload the file to specific dst.
	c.SaveUploadedFile(file, dst)
}
curl -X POST http://localhost:8080/upload \
  -F "upload[]=@/Users/appleboy/test1.zip" \
  -F "upload[]=@/Users/appleboy/test2.zip" \
  -H "Content-Type: multipart/form-data"

func (*Context) ServeFile

func (ctx *Context) ServeFile(filePath string)

func (*Context) Set

func (c *Context) Set(name string, value interface{})

Set is used to store a new key/value pair exclusively for this context.

func (*Context) SetCookie

func (ctx *Context) SetCookie(name string, value string, others ...interface{})

name/value escape by url.QueryEscape() before SetCookie() if necessary others... : MaxAge, Path, Domain, Secure, HttpOnly, SameSite. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.

func (*Context) SetHeader

func (ctx *Context) SetHeader(key, value string)

func (*Context) Status

func (ctx *Context) Status() int

func (*Context) Stream

func (ctx *Context) Stream(contentType string, r io.Reader) error

func (*Context) String

func (ctx *Context) String(code int, str string)

func (*Context) Unauthorized

func (ctx *Context) Unauthorized()

401

func (*Context) UserAgent

func (ctx *Context) UserAgent() string

func (*Context) Write

func (ctx *Context) Write(data []byte) (int, error)

func (*Context) WriteHeader

func (ctx *Context) WriteHeader(code int)

func (*Context) Written

func (ctx *Context) Written() bool

func (*Context) XML

func (ctx *Context) XML(code int, v interface{}) error

type ETagType

type ETagType byte

type Engine

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

--- water ---

func (*Engine) ListenAndServe

func (e *Engine) ListenAndServe(addr string) error

Run start web service Deprecated: please use Run()

func (*Engine) ListenAndServeTLS

func (e *Engine) ListenAndServeTLS(addr, certFile, keyFile string) error

Run start web service with tls Deprecated: please use RunTLS()

func (*Engine) PrintRawAllRoutes

func (e *Engine) PrintRawAllRoutes()

order by add router order output: [method : count(handler)] uri

func (*Engine) PrintRawRouter

func (e *Engine) PrintRawRouter()

output: uri [method : count(handler)]

func (*Engine) PrintRawRoutes

func (e *Engine) PrintRawRoutes(method string)

print routes by method order by uri output: [count(handler)] uri

func (*Engine) PrintRouterTree

func (e *Engine) PrintRouterTree(method string)

print release router tree by method len(tree.handlers) includes middleware

func (*Engine) Run

func (e *Engine) Run(addr ...string) error

Run start web service defualt port is ":8080"

func (*Engine) RunTLS

func (e *Engine) RunTLS(addr, certFile, keyFile string) error

Run start web service with tls

func (*Engine) ServeHTTP

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

type Environ

type Environ map[string]interface{}

a set of environment variables. 存储water的环境变量

func (Environ) Get

func (m Environ) Get(name string) interface{}

panic if name not exist

func (Environ) GetBool

func (m Environ) GetBool(name string) bool

func (Environ) GetFloat64

func (m Environ) GetFloat64(name string) float64

func (Environ) GetInt

func (m Environ) GetInt(name string) int

func (Environ) GetInt64

func (m Environ) GetInt64(name string) int64

func (Environ) GetString

func (m Environ) GetString(name string) string

func (Environ) GetUint

func (m Environ) GetUint(name string) uint

func (Environ) GetUint64

func (m Environ) GetUint64(name string) uint64

func (Environ) Has

func (m Environ) Has(name string) bool

func (Environ) Set

func (m Environ) Set(name string, v interface{})

panic if name already exists

type H

type H map[string]interface{}

type Handler

type Handler interface {
	ServeHTTP(*Context)
}

func WrapHandler

func WrapHandler(handler interface{}) Handler

WrapHandlerFunc wrap func to HandlerFunc

type HandlerFunc

type HandlerFunc func(*Context)

func CORS

func CORS(config CORSConfig) HandlerFunc

func Logger

func Logger() HandlerFunc

func Recovery

func Recovery() HandlerFunc

func (HandlerFunc) ServeHTTP

func (f HandlerFunc) ServeHTTP(ctx *Context)

type Option

type Option func(*options)

func WithMaxMultipartMemory

func WithMaxMultipartMemory(max int64) Option

WithMaxMultipartMemory is given to http.Request's ParseMultipartForm method call.

func WithNoFoundHandlers

func WithNoFoundHandlers(hs ...interface{}) Option

WithNoFoundHandlers the handler for no match route, example: vue spa code=404, can use middleware

func WithStaticRouter

func WithStaticRouter(enable bool) Option

WithStaticRouter for the scene of multi status route 适用于多静态路由的场景

type Params

type Params map[string]string

func (Params) Bool

func (p Params) Bool(name string) (bool, error)

Bool return bool with error.

func (Params) Float64

func (p Params) Float64(name string) (float64, error)

Float64 returns float64 with error.

func (Params) Int

func (p Params) Int(name string) (int, error)

Int return int with error.

func (Params) Int64

func (p Params) Int64(name string) (int64, error)

Int64 returns int64 with error.

func (Params) MustBool

func (p Params) MustBool(name string) bool

MustBool returns bool.

func (Params) MustFloat64

func (p Params) MustFloat64(name string) float64

MustFloat64 returns float64l

func (Params) MustInt

func (p Params) MustInt(name string) int

MustInt returns int.

func (Params) MustInt64

func (p Params) MustInt64(name string) int64

MustInt64 returns int64.

func (Params) MustUint

func (p Params) MustUint(name string) uint

MustUint returns uint.

func (Params) MustUint64

func (p Params) MustUint64(name string) uint64

MustUint64 returns uint64.

func (Params) String

func (p Params) String(name string) string

String returns value by given param name. panic if param not exits

func (Params) Uint

func (p Params) Uint(name string) (uint, error)

Uint returns uint with error.

func (Params) Uint64

func (p Params) Uint64(name string) (uint64, error)

Uint64 returns uint64 with error.

type Render

type Render interface {
	HTMLSet(*Context, int, string, string, interface{})
}

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
}

type Router

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

multiway tree

func Default

func Default() *Router

Default returns an router instance with the Logger and Recovery middleware already attached.

func NewRouter

func NewRouter() *Router

func (*Router) ANY

func (r *Router) ANY(pattern string, handlers ...interface{})

func (*Router) Before

func (r *Router) Before(handlers ...interface{})

Before for global middleware, include handle middleware before match routes and 404

func (*Router) Classic

func (r *Router) Classic()

func (*Router) DELETE

func (r *Router) DELETE(pattern string, handlers ...interface{})

func (*Router) GET

func (r *Router) GET(pattern string, handlers ...interface{})

func (*Router) Group

func (r *Router) Group(pattern string, is ...interface{}) *Router

func (*Router) HEAD

func (r *Router) HEAD(pattern string, handlers ...interface{})

func (*Router) Handler

func (r *Router) Handler(opts ...Option) *Engine

to generate router tree. r is root router.

func (*Router) IsParent

func (r *Router) IsParent() bool

func (*Router) OPTIONS

func (r *Router) OPTIONS(pattern string, handlers ...interface{})

func (*Router) PATCH

func (r *Router) PATCH(pattern string, handlers ...interface{})

func (*Router) POST

func (r *Router) POST(pattern string, handlers ...interface{})

func (*Router) PUT

func (r *Router) PUT(pattern string, handlers ...interface{})

func (*Router) Static

func (r *Router) Static(uri, root string)

Static serves files from the given file system root. http.NotFound is used instead of the Router's NotFound handler. use :

router.Static("/static", "/var/www")

func (*Router) StaticAdvance

func (r *Router) StaticAdvance(opt *StaticOptions)

Static serves files from the given file system root. http.NotFound is used instead of the Router's NotFound handler. can send expires, etag, index

func (*Router) StaticFile

func (r *Router) StaticFile(relativePath, filepath string)

StaticFile registers a single route in order to serve a single file router.StaticFile("favicon.ico", "./resources/favicon.ico")

func (*Router) Use

func (r *Router) Use(handlers ...interface{})

type StaticOptions

type StaticOptions struct {
	// Prefix is the optional prefix used to serve the static directory content
	Prefix string
	// IndexFile defines which file to serve as index if it exists.
	IndexFile string

	// Expires defines which user-defined function to use for producing a HTTP Expires Header
	Expires func() string
	// ETag defines if we should add an ETag header
	ETag ETagType
	// FileSystem is the interface for supporting any implmentation of file system.
	FileSystem http.FileSystem
	// contains filtered or unexported fields
}

StaticOptions is a struct for specifying configuration options for the Static Files middleware.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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