web

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: May 6, 2020 License: MIT Imports: 25 Imported by: 0

README

Web

  • golang workframe
  • support router
  • auto register router
  • micro serve
  • easy run
  • support go module go.mod

examples


package main

import (
	"github.com/xs23933/web"
)

//handler.go
type Handler struct {
    web.Handler
}

// Init Init
func (h *Handler) Init() {
	h.SetPrefix("/api") // Add prefix
}

func (h *Handler) Get_(ctx *web.Ctx) {
    ctx.Send("Hello world")
}

func(h *Handler) GetParams(ctx *web.Ctx) {
    ctx.Send("Param: ", ctx.Params("param"))
}

// PostParam PostParam
func (h *Handler) PostParam(ctx *web.Ctx) {
	ctx.Send("Param ", ctx.Params("param"))
}

// PutParams 可选参数
// put /:param?
func (h *Handler) PutParams(ctx *web.Ctx) {
	ctx.Send("Param? ", ctx.Params("param"))
}

// main.go
func main(){
    app := web.New(&web.Options{Debug: true})

    app.Use(new(Handler))
    // Serve(port) 
    if err := app.Serve(80); err != nil {
        panic(err)
    }
}


go run example/main.go

+ ---- Auto register router ---- +
| GET	/api/authorize
| GET	/api/user/info
| POST	/api/:param
| PUT	/api/:param?
+ ------------------------------ +
Started server on 0.0.0.0:80

Documentation

Index

Constants

View Source
const (
	MIMETextXML   = "text/xml"
	MIMETextHTML  = "text/html"
	MIMETextPlain = "text/plain"

	MIMEApplicationJSON       = "application/json"
	MIMEApplicationJavaScript = "application/javascript"
	MIMEApplicationXML        = "application/xml"
	MIMEApplicationForm       = "application/x-www-form-urlencoded"

	MIMEMultipartForm = "multipart/form-data"

	MIMEOctetStream = "application/octet-stream"
)

MIME types were copied from labstack/echo

View Source
const (
	// Authentication
	HeaderAuthorization      = "Authorization"
	HeaderProxyAuthenticate  = "Proxy-Authenticate"
	HeaderProxyAuthorization = "Proxy-Authorization"
	HeaderWWWAuthenticate    = "WWW-Authenticate"

	// Caching
	HeaderAge           = "Age"
	HeaderCacheControl  = "Cache-Control"
	HeaderClearSiteData = "Clear-Site-Data"
	HeaderExpires       = "Expires"
	HeaderPragma        = "Pragma"
	HeaderWarning       = "Warning"

	// Client hints
	HeaderAcceptCH         = "Accept-CH"
	HeaderAcceptCHLifetime = "Accept-CH-Lifetime"
	HeaderContentDPR       = "Content-DPR"
	HeaderDPR              = "DPR"
	HeaderEarlyData        = "Early-Data"
	HeaderSaveData         = "Save-Data"
	HeaderViewportWidth    = "Viewport-Width"
	HeaderWidth            = "Width"

	// Conditionals
	HeaderETag              = "ETag"
	HeaderIfMatch           = "If-Match"
	HeaderIfModifiedSince   = "If-Modified-Since"
	HeaderIfNoneMatch       = "If-None-Match"
	HeaderIfUnmodifiedSince = "If-Unmodified-Since"
	HeaderLastModified      = "Last-Modified"
	HeaderVary              = "Vary"

	// Connection management
	HeaderConnection = "Connection"
	HeaderKeepAlive  = "Keep-Alive"

	// Content negotiation
	HeaderAccept         = "Accept"
	HeaderAcceptCharset  = "Accept-Charset"
	HeaderAcceptEncoding = "Accept-Encoding"
	HeaderAcceptLanguage = "Accept-Language"

	// Controls
	HeaderCookie      = "Cookie"
	HeaderExpect      = "Expect"
	HeaderMaxForwards = "Max-Forwards"
	HeaderSetCookie   = "Set-Cookie"

	// CORS
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderOrigin                        = "Origin"
	HeaderTimingAllowOrigin             = "Timing-Allow-Origin"
	HeaderXPermittedCrossDomainPolicies = "X-Permitted-Cross-Domain-Policies"

	// Do Not Track
	HeaderDNT = "DNT"
	HeaderTk  = "Tk"

	// Downloads
	HeaderContentDisposition = "Content-Disposition"

	// Message body information
	HeaderContentEncoding = "Content-Encoding"
	HeaderContentLanguage = "Content-Language"
	HeaderContentLength   = "Content-Length"
	HeaderContentLocation = "Content-Location"
	HeaderContentType     = "Content-Type"

	// Proxies
	HeaderForwarded       = "Forwarded"
	HeaderVia             = "Via"
	HeaderXForwardedFor   = "X-Forwarded-For"
	HeaderXForwardedHost  = "X-Forwarded-Host"
	HeaderXForwardedProto = "X-Forwarded-Proto"

	// Redirects
	HeaderLocation = "Location"

	// Request context
	HeaderFrom           = "From"
	HeaderHost           = "Host"
	HeaderReferer        = "Referer"
	HeaderReferrerPolicy = "Referrer-Policy"
	HeaderUserAgent      = "User-Agent"

	// Response context
	HeaderAllow  = "Allow"
	HeaderServer = "Server"

	// Range requests
	HeaderAcceptRanges = "Accept-Ranges"
	HeaderContentRange = "Content-Range"
	HeaderIfRange      = "If-Range"
	HeaderRange        = "Range"

	// Security
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderCrossOriginResourcePolicy       = "Cross-Origin-Resource-Policy"
	HeaderExpectCT                        = "Expect-CT"
	HeaderFeaturePolicy                   = "Feature-Policy"
	HeaderPublicKeyPins                   = "Public-Key-Pins"
	HeaderPublicKeyPinsReportOnly         = "Public-Key-Pins-Report-Only"
	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderUpgradeInsecureRequests         = "Upgrade-Insecure-Requests"
	HeaderXContentTypeOptions             = "X-Content-Type-Options"
	HeaderXDownloadOptions                = "X-Download-Options"
	HeaderXFrameOptions                   = "X-Frame-Options"
	HeaderXPoweredBy                      = "X-Powered-By"
	HeaderXXSSProtection                  = "X-XSS-Protection"

	// Server-sent event
	HeaderLastEventID = "Last-Event-ID"
	HeaderNEL         = "NEL"
	HeaderPingFrom    = "Ping-From"
	HeaderPingTo      = "Ping-To"
	HeaderReportTo    = "Report-To"

	// Transfer coding
	HeaderTE               = "TE"
	HeaderTrailer          = "Trailer"
	HeaderTransferEncoding = "Transfer-Encoding"

	// WebSockets
	HeaderSecWebSocketAccept     = "Sec-WebSocket-Accept"
	HeaderSecWebSocketExtensions = "Sec-WebSocket-Extensions"
	HeaderSecWebSocketKey        = "Sec-WebSocket-Key"
	HeaderSecWebSocketProtocol   = "Sec-WebSocket-Protocol"
	HeaderSecWebSocketVersion    = "Sec-WebSocket-Version"

	// Other
	HeaderAcceptPatch         = "Accept-Patch"
	HeaderAcceptPushPolicy    = "Accept-Push-Policy"
	HeaderAcceptSignature     = "Accept-Signature"
	HeaderAltSvc              = "Alt-Svc"
	HeaderDate                = "Date"
	HeaderIndex               = "Index"
	HeaderLargeAllocation     = "Large-Allocation"
	HeaderLink                = "Link"
	HeaderPushPolicy          = "Push-Policy"
	HeaderRetryAfter          = "Retry-After"
	HeaderServerTiming        = "Server-Timing"
	HeaderSignature           = "Signature"
	HeaderSignedHeaders       = "Signed-Headers"
	HeaderSourceMap           = "SourceMap"
	HeaderUpgrade             = "Upgrade"
	HeaderXDNSPrefetchControl = "X-DNS-Prefetch-Control"
	HeaderXPingback           = "X-Pingback"
	HeaderXRequestID          = "X-Request-ID"
	HeaderXRequestedWith      = "X-Requested-With"
	HeaderXRobotsTag          = "X-Robots-Tag"
	HeaderXUACompatible       = "X-UA-Compatible"
)

HTTP Headers were copied from net/http.

View Source
const (
	TextBlack = iota + 30
	TextRed
	TextGreen
	TextYellow
	TextBlue
	TextMagenta
	TextCyan
	TextWhite
)

Variables

This section is empty.

Functions

func Black

func Black(msg string) string

func Blue

func Blue(msg string) string

func Cyan

func Cyan(msg string) string

func Green

func Green(msg string) string

func Magenta

func Magenta(msg string) string

func Red

func Red(msg string) string

func SetColor

func SetColor(msg string, conf, bg, text int) string

func White

func White(msg string) string

func Yellow

func Yellow(msg string) string

Types

type Cookie struct {
	Name     string
	Value    string
	Path     string
	Domain   string
	Expires  time.Time
	Secure   bool
	HTTPOnly bool
	SameSite string
}

Cookie struct

type Core

type Core struct {
	*Options
	*fasthttp.Server
	// contains filtered or unexported fields
}

Core core class

func New

func New(opts ...*Options) *Core

New new core

func (*Core) Serve

func (c *Core) Serve(address interface{}, tlsopt ...*tls.Config) error

Serve 启动

func (*Core) Use

func (c *Core) Use(args ...interface{}) *Core

Use registers a middleware route.

type Ctx

type Ctx struct {
	*Core
	*fasthttp.RequestCtx
	*Route
	// contains filtered or unexported fields
}

Ctx web context

func (*Ctx) Body

func (c *Ctx) Body() string

Body contains the raw body submitted in a POST request. If a key is provided, it returns the form value 获得某个值用 c.FormValue

func (*Ctx) ClearCookie

func (c *Ctx) ClearCookie(key ...string)

ClearCookie expires a specific cookie by key. If no key is provided it expires all cookies.

func (*Ctx) Cookie

func (c *Ctx) Cookie(cookie *Cookie)

Cookie sets a cookie by passing a cookie struct

func (*Ctx) Cookies

func (c *Ctx) Cookies(key ...string) (value string)

Cookies is used for getting a cookie value by key

func (*Ctx) Download

func (c *Ctx) Download(file string, name ...string)

Download transfers the file from path as an attachment. Typically, browsers will prompt the user for download. By default, the Content-Disposition header filename= parameter is the filepath (this typically appears in the browser dialog). Override this default with the filename parameter.

func (*Ctx) FormValue

func (c *Ctx) FormValue(k string) (v string)

FormValue 读取 form的值

func (*Ctx) Fresh

func (c *Ctx) Fresh() bool

Fresh When the response is still “fresh” in the client’s cache true is returned, otherwise false is returned to indicate that the client cache is now stale and the full response should be sent. When a client sends the Cache-Control: no-cache request header to indicate an end-to-end reload request, this module will return false to make handling these requests transparent. https://github.com/jshttp/fresh/blob/10e0471669dbbfbfd8de65bc6efac2ddd0bfa057/index.js#L33

func (*Ctx) Get

func (c *Ctx) Get(k string) string

Get the http request header specified by field

func (Ctx) Host

func (c Ctx) Host() string

Host contains the hostname derived from the Host HTTP header.

func (*Ctx) IP

func (c *Ctx) IP() string

IP returns the remote IP address of the request.

func (*Ctx) IPs

func (c *Ctx) IPs() []string

IPs returns an string slice of IP addresses specified in the X-Forwarded-For request header.

func (*Ctx) JSON

func (c *Ctx) JSON(data interface{}) error

JSON 发送 json 数据

func (*Ctx) JSONP

func (c *Ctx) JSONP(data interface{}, callback ...string) error

JSONP 发送jsonp 数据

func (*Ctx) Next

func (c *Ctx) Next(err ...error)

Next 执行下一个操作

func (*Ctx) Params

func (c *Ctx) Params(k string) (v string)

Params is used to get the route parameters.

func (*Ctx) Path

func (c *Ctx) Path() string

Path 返回path

func (*Ctx) Query

func (c *Ctx) Query(k string) (value string)

Query returns the query string parameter in the url.

func (*Ctx) ReadBody

func (c *Ctx) ReadBody(out interface{}) error

ReadBody 读取body 数据

func (*Ctx) Redirect

func (c *Ctx) Redirect(path string, status ...int)

Redirect 页面跳转

func (*Ctx) SaveFile

func (c *Ctx) SaveFile(fileheader *multipart.FileHeader, path string) error

SaveFile saves any multipart file to disk.

func (*Ctx) Send

func (c *Ctx) Send(bodies ...interface{})

Send sets the HTTP response body. The Send body can be of any type.

func (*Ctx) SendFile

func (c *Ctx) SendFile(file string, noCompression ...bool)

SendFile transfers the from the give path.

func (*Ctx) SendStatus

func (c *Ctx) SendStatus(code int)

SendStatus 发送 http code

func (*Ctx) Set

func (c *Ctx) Set(k, v string)

Set ctx set header

func (*Ctx) Vars

func (c *Ctx) Vars(k string, v ...interface{}) (val interface{})

Vars 本地数据

func (*Ctx) Write

func (c *Ctx) Write(bodies ...interface{})

Write appends any input to the HTTP body response.

type Handler

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

Handler 基础分类

func (*Handler) Init

func (h *Handler) Init()

Init 初始化操作

func (*Handler) Prefix

func (h *Handler) Prefix() string

Prefix 初始化操作

func (*Handler) Preload

func (h *Handler) Preload(c *Ctx)

Preload 预处理使用 必须配置 Next结尾

func (*Handler) SetPrefix

func (h *Handler) SetPrefix(prefix string)

SetPrefix 设置前缀

type Options

type Options struct {
	Prefork bool // multiple go processes listening on the some port
	// ETag 发送etag
	ETag       bool
	ServerName string
	// Fasthttp options
	Concurrency        int // default: 256 * 1024
	NoDefaultDate      bool
	DisableKeepalive   bool
	ReadTimeout        time.Duration
	WriteTimeout       time.Duration
	IdleTimeout        time.Duration
	MaxRequestBodySize int
	Debug              bool
}

Options all options

type Route

type Route struct {
	Method string         // http method
	Path   string         // original path
	Params []string       // path params
	Regexp *regexp.Regexp // regexp matcher

	Handler func(*Ctx) // ctx handler
	// contains filtered or unexported fields
}

Route 路由

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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