volta

package module
v1.0.7 Latest Latest
Warning

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

Go to latest
Published: Jan 21, 2023 License: MIT Imports: 12 Imported by: 0

README

Go Reference

volta

⚡️ A full-featured wrapper over the http server presented in the golang standard library.

Installation

 go get github.com/govolta/volta

Usage

package main

import (
    "github.com/govolta/volta"
    "github.com/govolta/volta/middleware/logger"
)

func main() {
    app := volta.New(volta.Config{
        Port:               "1337",
        RoutePathCaching:   true,
        TemplateAutoReload: true,
    })
    
    app.LoadTemplates("./example/templates", ".html", true)
    
    app.Use(logger.New())
    
    app.Get("/home", func(ctx *volta.Ctx) error {
        return ctx.HTML("template.html", volta.Map{
            "Title": func() string {
                return "Hello, World!"
            },
        })
    })
    
    app.Run()
}

Features

  • Custom Parametric Router
  • Groups Routing
  • Middlewares

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoJSONMarshaler is returned when no JSON marshaler is set
	ErrorNoJSONMarshaler = errors.New("no JSON marshaller set")
	ErrorNext            = errors.New("skip to next handler")
	ErrorNoLocal         = errors.New("no local found")
)
View Source
var (
	DefaultConfig = Config{
		Port:               "8080",
		RoutePathCaching:   true,
		TemplateAutoReload: false,
		JsonMarshaler:      json.Marshal,
		JsonUnmarshaler:    json.Unmarshal,
	}
)

Functions

func ErrorMessage added in v1.0.7

func ErrorMessage(msg string)

func LogMessage added in v1.0.7

func LogMessage(msg string)

Types

type App

type App struct {
	Conf Config
	// contains filtered or unexported fields
}

func New

func New(conf Config) *App

func (*App) Delete

func (a *App) Delete(path string, handler ...Handler)

func (*App) Get

func (a *App) Get(path string, handler ...Handler)

func (*App) Group

func (a *App) Group(path string, handler ...Handler) Group

func (*App) LoadTemplates added in v1.0.7

func (a *App) LoadTemplates(path, extension string, recursive bool)

func (*App) Options

func (a *App) Options(path string, handler ...Handler)

func (*App) Patch

func (a *App) Patch(path string, handler ...Handler)

func (*App) Post

func (a *App) Post(path string, handler ...Handler)

func (*App) Put

func (a *App) Put(path string, handler ...Handler)

func (*App) Run

func (a *App) Run()

func (*App) ServeHTTP added in v1.0.6

func (a *App) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*App) Stop

func (a *App) Stop()

func (*App) Use

func (a *App) Use(handlers ...Handler)

type Config

type Config struct {
	Port               string
	RoutePathCaching   bool
	TemplateAutoReload bool
	JsonMarshaler      JSONMarshal
	JsonUnmarshaler    JSONUnmarshal
}

Config Volta Wrapper configuration struct

type Ctx

type Ctx struct {
	Response http.ResponseWriter
	Request  *http.Request
	// contains filtered or unexported fields
}

func NewCtx added in v1.0.6

func NewCtx(w http.ResponseWriter, r *http.Request, params []Param, handlers []Handler, app *App) *Ctx

func (*Ctx) Bind added in v1.0.7

func (a *Ctx) Bind(i Map)

func (*Ctx) Body

func (a *Ctx) Body() ([]byte, error)

Body returns the request body bytes.

func (*Ctx) CurrentRoute

func (a *Ctx) CurrentRoute() string

func (*Ctx) Form

func (a *Ctx) Form(key, def string) string

Form returns the value of the form field with the given name.

func (*Ctx) FormFile

func (a *Ctx) FormFile(key string) (multipart.File, error)

FormFile Form returns the value of the form file field with the given name.

func (*Ctx) GetLocal added in v1.0.7

func (a *Ctx) GetLocal(key string) (interface{}, error)

func (*Ctx) GetLocals added in v1.0.7

func (a *Ctx) GetLocals() Map

func (*Ctx) GetReqHeaders

func (a *Ctx) GetReqHeaders() map[string][]string

GetReqHeaders returns all request headers.

func (*Ctx) HTML added in v1.0.7

func (a *Ctx) HTML(file string, data Map) error

func (*Ctx) Header

func (a *Ctx) Header(key, def string) string

Header returns the value of the header field with the given name.

func (*Ctx) Host

func (a *Ctx) Host() string

Host returns the host.

func (*Ctx) IsDelete

func (a *Ctx) IsDelete() bool

IsDelete returns true if the request method is DELETE.

func (*Ctx) IsFromLocal

func (a *Ctx) IsFromLocal() bool

IsFromLocal returns true if request is from localhost.

func (*Ctx) IsGet

func (a *Ctx) IsGet() bool

IsGet returns true if the request method is GET.

func (*Ctx) IsOptions

func (a *Ctx) IsOptions() bool

IsOptions returns true if the request method is OPTIONS.

func (*Ctx) IsPatch

func (a *Ctx) IsPatch() bool

IsPatch returns true if the request method is PATCH.

func (*Ctx) IsPost

func (a *Ctx) IsPost() bool

IsPost returns true if the request method is POST.

func (*Ctx) IsPut

func (a *Ctx) IsPut() bool

IsPut returns true if the request method is PUT.

func (*Ctx) Method

func (a *Ctx) Method() string

Method returns the request method.

func (*Ctx) Next

func (a *Ctx) Next() error

func (*Ctx) Param

func (a *Ctx) Param(key, def string) string

Param returns the value of the param field with the given name.

func (*Ctx) Query

func (a *Ctx) Query(key, def string) string

Query returns the value of the query field with the given name.

func (*Ctx) Redirect

func (a *Ctx) Redirect(url string) error

Redirect redirects to the given url.

func (*Ctx) RedirectStatus

func (a *Ctx) RedirectStatus(url string, status int) error

RedirectStatus redirects to the given url with the given status.

func (*Ctx) RemoteAddr

func (a *Ctx) RemoteAddr() string

RemoteAddr return client IP address.

func (*Ctx) RemoveLocal added in v1.0.7

func (a *Ctx) RemoveLocal(key string)

func (*Ctx) SaveFile

func (a *Ctx) SaveFile(file multipart.File, path string) error

SaveFile saves the file to the given path.

func (*Ctx) Send

func (a *Ctx) Send(msg []byte) error

Send sends a byte array response.

func (*Ctx) SendJSON

func (a *Ctx) SendJSON(msg Map) error

SendJSON sends a JSON response.

func (*Ctx) SendString

func (a *Ctx) SendString(msg string) error

SendString sends a string response.

func (*Ctx) SetHeader

func (a *Ctx) SetHeader(key, val string) *Ctx

SetHeader sets the header with the given key and value.

func (*Ctx) SetLocal added in v1.0.7

func (a *Ctx) SetLocal(key string, val interface{}) *Ctx

func (*Ctx) Status

func (a *Ctx) Status(status Status) *Ctx

Status sets the status code.

func (*Ctx) UserAgent

func (a *Ctx) UserAgent() string

UserAgent returns the user agent.

type Group

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

func (*Group) Delete

func (a *Group) Delete(path string, handler ...Handler)

func (*Group) Get

func (a *Group) Get(path string, handler ...Handler)

func (*Group) Options

func (a *Group) Options(path string, handler ...Handler)

func (*Group) Patch

func (a *Group) Patch(path string, handler ...Handler)

func (*Group) Post

func (a *Group) Post(path string, handler ...Handler)

func (*Group) Put

func (a *Group) Put(path string, handler ...Handler)

type Handler

type Handler func(*Ctx) error
type Header string
var (
	HeaderAuthorization                   Header = "Authorization"
	HeaderProxyAuthenticate               Header = "Proxy-Authenticate"
	HeaderProxyAuthorization              Header = "Proxy-Authorization"
	HeaderWWWAuthenticate                 Header = "WWW-Authenticate"
	HeaderAge                             Header = "Age"
	HeaderCacheControl                    Header = "Cache-Control"
	HeaderClearSiteData                   Header = "Clear-Site-Data"
	HeaderExpires                         Header = "Expires"
	HeaderPragma                          Header = "Pragma"
	HeaderWarning                         Header = "Warning"
	HeaderAcceptCH                        Header = "Accept-CH"
	HeaderAcceptCHLifetime                Header = "Accept-CH-Lifetime"
	HeaderContentDPR                      Header = "Content-DPR"
	HeaderDPR                             Header = "DPR"
	HeaderEarlyData                       Header = "Early-Data"
	HeaderSaveData                        Header = "Save-Data"
	HeaderViewportWidth                   Header = "Viewport-Width"
	HeaderWidth                           Header = "Width"
	HeaderETag                            Header = "ETag"
	HeaderIfMatch                         Header = "If-Match"
	HeaderIfModifiedSince                 Header = "If-Modified-Since"
	HeaderIfNoneMatch                     Header = "If-None-Match"
	HeaderIfUnmodifiedSince               Header = "If-Unmodified-Since"
	HeaderLastModified                    Header = "Last-Modified"
	HeaderVary                            Header = "Vary"
	HeaderConnection                      Header = "Connection"
	HeaderKeepAlive                       Header = "Keep-Alive"
	HeaderAccept                          Header = "Accept"
	HeaderAcceptCharset                   Header = "Accept-Charset"
	HeaderAcceptEncoding                  Header = "Accept-Encoding"
	HeaderAcceptLanguage                  Header = "Accept-Language"
	HeaderCookie                          Header = "Cookie"
	HeaderExpect                          Header = "Expect"
	HeaderMaxForwards                     Header = "Max-Forwards"
	HeaderSetCookie                       Header = "Set-Cookie"
	HeaderAccessControlAllowCredentials   Header = "Access-Control-Allow-Credentials"
	HeaderAccessControlAllowHeaders       Header = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowMethods       Header = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowOrigin        Header = "Access-Control-Allow-Origin"
	HeaderAccessControlExposeHeaders      Header = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge             Header = "Access-Control-Max-Age"
	HeaderAccessControlRequestHeaders     Header = "Access-Control-Request-Headers"
	HeaderAccessControlRequestMethod      Header = "Access-Control-Request-Method"
	HeaderOrigin                          Header = "Origin"
	HeaderTimingAllowOrigin               Header = "Timing-Allow-Origin"
	HeaderXPermittedCrossDomainPolicies   Header = "X-Permitted-Cross-Domain-Policies"
	HeaderDNT                             Header = "DNT"
	HeaderTk                              Header = "Tk"
	HeaderContentDisposition              Header = "Content-Disposition"
	HeaderContentEncoding                 Header = "Content-Encoding"
	HeaderContentLanguage                 Header = "Content-Language"
	HeaderContentLength                   Header = "Content-Length"
	HeaderContentLocation                 Header = "Content-Location"
	HeaderContentType                     Header = "Content-Type"
	HeaderForwarded                       Header = "Forwarded"
	HeaderVia                             Header = "Via"
	HeaderXForwardedFor                   Header = "X-Forwarded-For"
	HeaderXForwardedHost                  Header = "X-Forwarded-Host"
	HeaderXForwardedProto                 Header = "X-Forwarded-Proto"
	HeaderXForwardedProtocol              Header = "X-Forwarded-Protocol"
	HeaderXForwardedSsl                   Header = "X-Forwarded-Ssl"
	HeaderXUrlScheme                      Header = "X-Url-Scheme"
	HeaderLocation                        Header = "Location"
	HeaderFrom                            Header = "From"
	HeaderHost                            Header = "Host"
	HeaderReferer                         Header = "Referer"
	HeaderReferrerPolicy                  Header = "Referrer-Policy"
	HeaderUserAgent                       Header = "User-Agent"
	HeaderAllow                           Header = "Allow"
	HeaderServer                          Header = "Server"
	HeaderAcceptRanges                    Header = "Accept-Ranges"
	HeaderContentRange                    Header = "Content-Range"
	HeaderIfRange                         Header = "If-Range"
	HeaderRange                           Header = "Range"
	HeaderContentSecurityPolicy           Header = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly Header = "Content-Security-Policy-Report-Only"
	HeaderCrossOriginResourcePolicy       Header = "Cross-Origin-Resource-Policy"
	HeaderExpectCT                        Header = "Expect-CT"
	HeaderFeaturePolicy                   Header = "Feature-Policy"
	HeaderPermissionsPolicy               Header = "Permissions-Policy"
	HeaderPublicKeyPins                   Header = "Public-Key-Pins"
	HeaderPublicKeyPinsReportOnly         Header = "Public-Key-Pins-Report-Only"
	HeaderStrictTransportSecurity         Header = "Strict-Transport-Security"
	HeaderUpgradeInsecureRequests         Header = "Upgrade-Insecure-Requests"
	HeaderXContentTypeOptions             Header = "X-Content-Type-Options"
	HeaderXDownloadOptions                Header = "X-Download-Options"
	HeaderXFrameOptions                   Header = "X-Frame-Options"
	HeaderXPoweredBy                      Header = "X-Powered-By"
	HeaderXXSSProtection                  Header = "X-XSS-Protection"
	HeaderLastEventID                     Header = "Last-Event-ID"
	HeaderNEL                             Header = "NEL"
	HeaderPingFrom                        Header = "Ping-From"
	HeaderPingTo                          Header = "Ping-To"
	HeaderReportTo                        Header = "Report-To"
	HeaderTE                              Header = "TE"
	HeaderTrailer                         Header = "Trailer"
	HeaderTransferEncoding                Header = "Transfer-Encoding"
	HeaderSecWebSocketAccept              Header = "Sec-WebSocket-Accept"
	HeaderSecWebSocketExtensions          Header = "Sec-WebSocket-Extensions"
	HeaderSecWebSocketKey                 Header = "Sec-WebSocket-Key"
	HeaderSecWebSocketProtocol            Header = "Sec-WebSocket-Protocol"
	HeaderSecWebSocketVersion             Header = "Sec-WebSocket-Version"
	HeaderAcceptPatch                     Header = "Accept-Patch"
	HeaderAcceptPushPolicy                Header = "Accept-Push-Policy"
	HeaderAcceptSignature                 Header = "Accept-Signature"
	HeaderAltSvc                          Header = "Alt-Svc"
	HeaderDate                            Header = "Date"
	HeaderIndex                           Header = "Index"
	HeaderLargeAllocation                 Header = "Large-Allocation"
	HeaderLink                            Header = "Link"
	HeaderPushPolicy                      Header = "Push-Policy"
	HeaderRetryAfter                      Header = "Retry-After"
	HeaderServerTiming                    Header = "Server-Timing"
	HeaderSignature                       Header = "Signature"
	HeaderSignedHeaders                   Header = "Signed-Headers"
	HeaderSourceMap                       Header = "SourceMap"
	HeaderUpgrade                         Header = "Upgrade"
	HeaderXDNSPrefetchControl             Header = "X-DNS-Prefetch-Control"
	HeaderXPingback                       Header = "X-Pingback"
	HeaderXRequestID                      Header = "X-Request-ID"
	HeaderXRequestedWith                  Header = "X-Requested-With"
	HeaderXRobotsTag                      Header = "X-Robots-Tag"
	HeaderXUACompatible                   Header = "X-UA-Compatible"
)

type JSONMarshal

type JSONMarshal func(v interface{}) ([]byte, error)

type JSONUnmarshal

type JSONUnmarshal func(data []byte, v interface{}) error

type Map

type Map map[string]interface{}

type Method added in v1.0.6

type Method string
var (
	GET     Method = "GET"
	POST    Method = "POST"
	PUT     Method = "PUT"
	DELETE  Method = "DELETE"
	PATCH   Method = "PATCH"
	OPTIONS Method = "OPTIONS"
)

type Param added in v1.0.6

type Param struct {
	Value string
	Name  string
}

type Route added in v1.0.6

type Route struct {
	Path       string
	PathTokens []pathToken
	Handlers   []Handler `json:"-"`

	Parametric bool
}

type Router added in v1.0.6

type Router struct {
	Routes     map[Method][]Route
	RouteCache map[Method]map[string]Route
	// contains filtered or unexported fields
}

type Status

type Status int
var (
	StatusSwitchingProtocols Status = 101
	StatusProcessing         Status = 102
	StatusEarlyHints         Status = 103

	StatusOK                   Status = 200
	StatusCreated              Status = 201
	StatusAccepted             Status = 202
	StatusNonAuthoritativeInfo Status = 203
	StatusNoContent            Status = 204
	StatusResetContent         Status = 205
	StatusPartialContent       Status = 206
	StatusMultiStatus          Status = 207
	StatusAlreadyReported      Status = 208

	StatusMultipleChoices   Status = 300
	StatusMovedPermanently  Status = 301
	StatusFound             Status = 302
	StatusSeeOther          Status = 303
	StatusNotModified       Status = 304
	StatusUseProxy          Status = 305
	StatusTemporaryRedirect Status = 307
	StatusPermanentRedirect Status = 308

	StatusBadRequest                  Status = 400
	StatusUnauthorized                Status = 401
	StatusPaymentRequired             Status = 402
	StatusForbidden                   Status = 403
	StatusNotFound                    Status = 404
	StatusMethodNotAllowed            Status = 405
	StatusNotAcceptable               Status = 406
	StatusProxyAuthRequired           Status = 407
	StatusRequestTimeout              Status = 408
	StatusConflict                    Status = 409
	StatusGone                        Status = 410
	StatusLengthRequired              Status = 411
	StatusPreconditionFailed          Status = 412
	StatusPayloadTooLarge             Status = 413
	StatusURITooLong                  Status = 414
	StatusUnsupportedMediaType        Status = 415
	StatusRangeNotSatisfiable         Status = 416
	StatusExpectationFailed           Status = 417
	StatusImATeapot                   Status = 418
	StatusMisdirectedRequest          Status = 421
	StatusUnprocessableEntity         Status = 422
	StatusLocked                      Status = 423
	StatusFailedDependency            Status = 424
	StatusTooEarly                    Status = 425
	StatusUpsgradeRequired            Status = 426
	StatusPreconditionRequired        Status = 428
	StatusTooManyRequests             Status = 429
	StatusRequestHeaderFieldsTooLarge Status = 431
	StatusUnavailableForLegalReasons  Status = 451

	StatusInternalServerError           Status = 500
	StatusNotImplemented                Status = 501
	StatusBadGateway                    Status = 502
	StatusServiceUnavailable            Status = 503
	StatusGatewayTimeout                Status = 504
	StatusHTTPVersionNotSupported       Status = 505
	StatusVariantAlsoNegotiates         Status = 506
	StatusInsufficientStorage           Status = 507
	StatusLoopDetected                  Status = 508
	StatusNotExtended                   Status = 510
	StatusNetworkAuthenticationRequired Status = 511
)

type Template added in v1.0.7

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

func NewTemplate added in v1.0.7

func NewTemplate(name, file string) *Template

func (*Template) Reload added in v1.0.7

func (t *Template) Reload()

Directories

Path Synopsis
middleware

Jump to

Keyboard shortcuts

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