gz

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2020 License: Apache-2.0 Imports: 35 Imported by: 0

README

gzcloud

介绍
软件架构

基于echo和scf-go-api-proxy源码

echo:

Commits on Jul 23, 2020

d3245067e0e02dafc7d14e17f5aa612711c30e83

本地更新时间:2020年7月24日10:49:37

scf-go-api-proxy:

只更新这个目录

https://github.com/linthan/scf-go-api-proxy/tree/master/core

db91d6333f4d54ae5d211bf6d096abc8baf111cf

本地更新时间:2020年7月21日18:01:09

使用说明
// go.mod
gitee.com/fulusco/gzcloud
package main

import (
	gz "gitee.com/fulusco/gzcloud"
	"gitee.com/fulusco/gzcloud/resource"
)

func getHanlder(c gz.Context) error {
	c.JSON(200, struct {
		Name    string
		Age     int
		Student struct {
			Clazz string
			Man   string
		}
	}{Name: "小红", Age: 22, Student: struct {
		Clazz string
		Man   string
	}{Clazz: "高三", Man: "王集"}})
	return nil
}

func main() {
	app := gz.Initialize(config)
	app.GET("/", getHanlder)
    // scf: 访问 https://xxxx/demo-gz/test
	app.GET("/test", getHanlder)
	app.GET("/de", getHanlder)
	app.GET("/de/", getHanlder)

	// 判断是web还是scf
	// 如果是scf则使用适配器
    // 这个是web和scf通用,都是这一种写法,根据配置来区分。
	app.Start(":8081")
}

// 配置,重点
var config = &resource.GzconfigStruct{
	Generator: true,
	Mode:      "scf",
	Active:    "dev", // prod
	Name:      "demo-gz",// 重点,这个是scf的函数名称,如果Mode为scf,路由会把/demo-gz作为前缀
	Banner: struct {
		Mode string // off on 隐藏、打印banner
		Text string // 自定义banner
	}{
		Mode: "on", // prod时设置为 off
	},
	Build: struct {
		Goos   string
		Goarch string
	}{
		Goos:   "windows",
		Goarch: "amd64",
	},
}

中间件 - 开发中...
开源协议 | License
  • echo:MIT

  • scf-go-api-proxy: Apache License 2.0

  • gzcloud: Apache License 2.0

码云特技
  1. 使用 Readme_XXX.md 来支持不同的语言,例如 Readme_en.md, Readme_zh.md
  2. 码云官方博客 blog.gitee.com
  3. 你可以 https://gitee.com/explore 这个地址来了解码云上的优秀开源项目
  4. GVP 全称是码云最有价值开源项目,是码云综合评定出的优秀开源项目
  5. 码云官方提供的使用手册 https://gitee.com/help
  6. 码云封面人物是一档用来展示码云会员风采的栏目 https://gitee.com/gitee-stars/

Documentation

Overview

Packge GzLambda add Application support for the aws-severless-go-api library. Uses the core package behind the scenes and exposes the New method to get a new instance and Proxy method to send request to the gz.Application scf适配器 - @see 配合 /scf_proxy

package gz implements high performance, minimalist Go web framework.

Example:

package main

import (
  "net/http"

  gz "gitee.com/fulusco/gzcloud"
  "github.com/labstack/echo/v4/middleware"
)

// Handler
func hello(c gz.Context) error {
  return c.String(http.StatusOK, "Hello, World!")
}

func main() {
  // Application instance
  e := gz.Initialize(nil)

  // Middleware
  e.Use(middleware.Logger())
  e.Use(middleware.Recover())

  // Routes
  e.GET("/", hello)

  // Start server
  e.Logger.Fatal(e.Start(":1323"))
}

Learn more at https://gz.labstack.com

Index

Constants

View Source
const (
	CONNECT = http.MethodConnect
	DELETE  = http.MethodDelete
	GET     = http.MethodGet
	HEAD    = http.MethodHead
	OPTIONS = http.MethodOptions
	PATCH   = http.MethodPatch
	POST    = http.MethodPost
	// PROPFIND = "PROPFIND"
	PUT   = http.MethodPut
	TRACE = http.MethodTrace
)

HTTP methods NOTE: Deprecated, please use the stdlib constants directly instead.

View Source
const (
	MODE_TYPE_SCF   = "scf"
	MODE_TYPE_WEB   = "web"
	URL_PREFIX_ROOT = "/"
)
View Source
const (
	MIMEApplicationJSON                  = "application/json"
	MIMEApplicationJSONCharsetUTF8       = MIMEApplicationJSON + "; " + charsetUTF8
	MIMEApplicationJavaScript            = "application/javascript"
	MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8
	MIMEApplicationXML                   = "application/xml"
	// "application/xml; charset=UTF-8"
	MIMEApplicationXMLCharsetUTF8 = MIMEApplicationXML + "; " + charsetUTF8
	MIMETextXML                   = "text/xml"
	MIMETextXMLCharsetUTF8        = MIMETextXML + "; " + charsetUTF8
	MIMEApplicationForm           = "application/x-www-form-urlencoded"
	MIMEApplicationProtobuf       = "application/protobuf"
	MIMEApplicationMsgpack        = "application/msgpack"
	MIMETextHTML                  = "text/html"
	MIMETextHTMLCharsetUTF8       = MIMETextHTML + "; " + charsetUTF8
	MIMETextPlain                 = "text/plain"
	MIMETextPlainCharsetUTF8      = MIMETextPlain + "; " + charsetUTF8
	MIMEMultipartForm             = "multipart/form-data"
	MIMEOctetStream               = "application/octet-stream"
)

MIME types

View Source
const (

	// PROPFIND Method can be used on collection and property resources.
	PROPFIND = "PROPFIND"
	// REPORT Method can be used to get information about a resource, see rfc 3253
	REPORT = "REPORT"
)
View Source
const (
	HeaderAccept              = "Accept"
	HeaderAcceptEncoding      = "Accept-Encoding"
	HeaderAllow               = "Allow"
	HeaderAuthorization       = "Authorization"
	HeaderContentDisposition  = "Content-Disposition"
	HeaderContentEncoding     = "Content-Encoding"
	HeaderContentLength       = "Content-Length"
	HeaderContentType         = "Content-Type"
	HeaderCookie              = "Cookie"
	HeaderSetCookie           = "Set-Cookie"
	HeaderIfModifiedSince     = "If-Modified-Since"
	HeaderLastModified        = "Last-Modified"
	HeaderLocation            = "Location"
	HeaderUpgrade             = "Upgrade"
	HeaderVary                = "Vary"
	HeaderWWWAuthenticate     = "WWW-Authenticate"
	HeaderXForwardedFor       = "X-Forwarded-For"
	HeaderXForwardedProto     = "X-Forwarded-Proto"
	HeaderXForwardedProtocol  = "X-Forwarded-Protocol"
	HeaderXForwardedSsl       = "X-Forwarded-Ssl"
	HeaderXUrlScheme          = "X-Url-Scheme"
	HeaderXHTTPMethodOverride = "X-HTTP-Method-Override"
	HeaderXRealIP             = "X-Real-IP"
	HeaderXRequestID          = "X-Request-ID"
	HeaderXRequestedWith      = "X-Requested-With"
	HeaderServer              = "Server"
	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"

	// Security
	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderXContentTypeOptions             = "X-Content-Type-Options"
	HeaderXXSSProtection                  = "X-XSS-Protection"
	HeaderXFrameOptions                   = "X-Frame-Options"
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderXCSRFToken                      = "X-CSRF-Token"
	HeaderReferrerPolicy                  = "Referrer-Policy"
)

Headers

View Source
const (
	// Version of Application
	Version = "4.1.16"
)

Variables

View Source
var (
	ErrUnsupportedMediaType        = NewHTTPError(http.StatusUnsupportedMediaType)
	ErrNotFound                    = NewHTTPError(http.StatusNotFound)
	ErrUnauthorized                = NewHTTPError(http.StatusUnauthorized)
	ErrForbidden                   = NewHTTPError(http.StatusForbidden)
	ErrMethodNotAllowed            = NewHTTPError(http.StatusMethodNotAllowed)
	ErrStatusRequestEntityTooLarge = NewHTTPError(http.StatusRequestEntityTooLarge)
	ErrTooManyRequests             = NewHTTPError(http.StatusTooManyRequests)
	ErrBadRequest                  = NewHTTPError(http.StatusBadRequest)
	ErrBadGateway                  = NewHTTPError(http.StatusBadGateway)
	ErrInternalServerError         = NewHTTPError(http.StatusInternalServerError)
	ErrRequestTimeout              = NewHTTPError(http.StatusRequestTimeout)
	ErrServiceUnavailable          = NewHTTPError(http.StatusServiceUnavailable)
	ErrValidatorNotRegistered      = errors.New("validator not registered")
	ErrRendererNotRegistered       = errors.New("renderer not registered")
	ErrInvalidRedirectCode         = errors.New("invalid redirect status code")
	ErrCookieNotFound              = errors.New("cookie not found")
	ErrInvalidCertOrKeyType        = errors.New("invalid cert or key type, must be string or []byte")
)

Errors

View Source
var (
	NotFoundHandler = func(c Context) error {
		return ErrNotFound
	}

	MethodNotAllowedHandler = func(c Context) error {
		return ErrMethodNotAllowed
	}
)

Error handlers

Functions

func GetPath

func GetPath(r *http.Request) string

GetPath returns RawPath, if it's empty returns Path from URL

Types

type Application

type Application struct {
	StdLogger *stdLog.Logger

	Server           *http.Server
	TLSServer        *http.Server
	Listener         net.Listener
	TLSListener      net.Listener
	AutoTLSManager   autocert.Manager
	DisableHTTP2     bool
	Debug            bool
	HideBanner       bool
	HidePort         bool
	HTTPErrorHandler HTTPErrorHandler
	Binder           Binder
	Validator        Validator
	Renderer         Renderer
	Logger           Logger
	IPExtractor      IPExtractor

	//	配置文件
	Config *resource.GzconfigStruct
	// contains filtered or unexported fields
}

Application is the top-level framework instance.

func Initialize

func Initialize(config *resource.GzconfigStruct) (app *Application)

New creates an instance of Application.

func (*Application) AcquireContext

func (app *Application) AcquireContext() Context

AcquireContext returns an empty `Context` instance from the pool. You must return the context by calling `ReleaseContext()`.

func (*Application) Add

func (app *Application) Add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

Add registers a new route for an HTTP method and path with matching handler in the router with optional route-level middleware.

func (*Application) AddMiddleware

func (app *Application) AddMiddleware(key string, middleware MiddlewareFunc)

func (*Application) Any

func (app *Application) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc) []*Route

Any registers a new route for all HTTP methods and path with matching handler in the router with optional route-level middleware.

func (*Application) CONNECT

func (app *Application) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

CONNECT registers a new CONNECT route for a path with matching handler in the router with optional route-level middleware.

func (*Application) Close

func (app *Application) Close() error

Close immediately stops the server. It internally calls `http.Server#Close()`.

func (*Application) DELETE

func (app *Application) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

DELETE registers a new DELETE route for a path with matching handler in the router with optional route-level middleware.

func (*Application) DefaultHTTPErrorHandler

func (app *Application) DefaultHTTPErrorHandler(err error, c Context)

DefaultHTTPErrorHandler is the default HTTP error handler. It sends a JSON response with status code.

func (*Application) File

func (app *Application) File(path, file string, m ...MiddlewareFunc) *Route

File registers a new route with path to serve a static file with optional route-level middleware.

func (*Application) GET

func (app *Application) GET(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

GET registers a new GET route for a path with matching handler in the router with optional route-level middleware.

func (*Application) Group

func (app *Application) Group(prefix string, m ...MiddlewareFunc) (g *Group)

Group creates a new router group with prefix and optional group-level middleware.

func (*Application) HEAD

func (app *Application) HEAD(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

HEAD registers a new HEAD route for a path with matching handler in the router with optional route-level middleware.

func (*Application) Host

func (app *Application) Host(name string, m ...MiddlewareFunc) (g *Group)

Host creates a new router group for the provided host and optional host-level middleware.

func (*Application) Match

func (app *Application) Match(methods []string, path string, handler HandlerFunc, middleware ...MiddlewareFunc) []*Route

Match registers a new route for multiple HTTP methods and path with matching handler in the router with optional route-level middleware.

func (*Application) NewContext

func (app *Application) NewContext(r *http.Request, w http.ResponseWriter) Context

NewContext returns a Context instance.

func (*Application) OPTIONS

func (app *Application) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

OPTIONS registers a new OPTIONS route for a path with matching handler in the router with optional route-level middleware.

func (*Application) PATCH

func (app *Application) PATCH(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

PATCH registers a new PATCH route for a path with matching handler in the router with optional route-level middleware.

func (*Application) POST

func (app *Application) POST(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

POST registers a new POST route for a path with matching handler in the router with optional route-level middleware.

func (*Application) PUT

func (app *Application) PUT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

PUT registers a new PUT route for a path with matching handler in the router with optional route-level middleware.

func (*Application) Pre

func (e *Application) Pre(middleware ...MiddlewareFunc)

Pre adds middleware to the chain which is run before router.

func (*Application) ReleaseContext

func (app *Application) ReleaseContext(c Context)

ReleaseContext returns the `Context` instance back to the pool. You must call it after `AcquireContext()`.

func (*Application) Remove

func (app *Application) Remove(key string)

TODO 使用map,<string,type> 可以进行删除

func (*Application) Reverse

func (app *Application) Reverse(name string, params ...interface{}) string

Reverse generates an URL from route name and provided parameters.

func (*Application) Router

func (e *Application) Router() *Router

Router returns the default router.

func (*Application) Routers

func (e *Application) Routers() map[string]*Router

Routers returns the map of host => router.

func (*Application) Routes

func (app *Application) Routes() []*Route

Routes returns the registered routes.

func (*Application) ServeHTTP

func (app *Application) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements `http.Handler` interface, which serves HTTP requests.

func (*Application) Shutdown

func (app *Application) Shutdown(ctx stdContext.Context) error

Shutdown stops the server gracefully. It internally calls `http.Server#Shutdown()`.

func (*Application) Start

func (app *Application) Start(address string) error

Start starts an HTTP server.

func (*Application) StartAutoTLS

func (app *Application) StartAutoTLS(address string) error

StartAutoTLS starts an HTTPS server using certificates automatically installed from https://letsencrypt.org.

func (*Application) StartH2CServer

func (app *Application) StartH2CServer(address string, h2s *http2.Server) (err error)

StartH2CServer starts a custom http/2 server with h2c (HTTP/2 Cleartext).

func (*Application) StartServer

func (app *Application) StartServer(s *http.Server) (err error)

StartServer starts a custom http server.

func (*Application) StartTLS

func (app *Application) StartTLS(address string, certFile, keyFile interface{}) (err error)

StartTLS starts an HTTPS server. If `certFile` or `keyFile` is `string` the values are treated as file paths. If `certFile` or `keyFile` is `[]byte` the values are treated as the certificate or key as-is.

func (*Application) Static

func (app *Application) Static(prefix, root string) *Route

Static registers a new route with path prefix to serve static files from the provided root directory.

func (*Application) TRACE

func (app *Application) TRACE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

TRACE registers a new TRACE route for a path with matching handler in the router with optional route-level middleware.

func (*Application) URI

func (app *Application) URI(handler HandlerFunc, params ...interface{}) string

URI generates a URI from handler.

func (*Application) URL

func (app *Application) URL(h HandlerFunc, params ...interface{}) string

URL is an alias for `URI` function.

func (*Application) Use

func (app *Application) Use(middleware ...MiddlewareFunc)

Deprecate: 请使用 AddMiddleware 方法

type BindUnmarshaler

type BindUnmarshaler interface {
	// UnmarshalParam decodes and assigns a value from an form or query param.
	UnmarshalParam(param string) error
}

BindUnmarshaler is the interface used to wrap the UnmarshalParam method. Types that don't implement this, but do implement encoding.TextUnmarshaler will use that interface instead.

type Binder

type Binder interface {
	Bind(i interface{}, c Context) error
}

Binder is the interface that wraps the Bind method.

type Context

type Context interface {
	// Request returns `*http.Request`.
	Request() *http.Request

	// SetRequest sets `*http.Request`.
	SetRequest(r *http.Request)

	// SetResponse sets `*Response`.
	SetResponse(r *Response)

	// Response returns `*Response`.
	Response() *Response

	// IsTLS returns true if HTTP connection is TLS otherwise false.
	IsTLS() bool

	// IsWebSocket returns true if HTTP connection is WebSocket otherwise false.
	IsWebSocket() bool

	// Scheme returns the HTTP protocol scheme, `http` or `https`.
	Scheme() string

	// RealIP returns the client's network address based on `X-Forwarded-For`
	// or `X-Real-IP` request header.
	// The behavior can be configured using `Application#IPExtractor`.
	RealIP() string

	// Path returns the registered path for the handler.
	Path() string

	// SetPath sets the registered path for the handler.
	SetPath(p string)

	// Param returns path parameter by name.
	Param(name string) string

	// ParamNames returns path parameter names.
	ParamNames() []string

	// SetParamNames sets path parameter names.
	SetParamNames(names ...string)

	// ParamValues returns path parameter values.
	ParamValues() []string

	// SetParamValues sets path parameter values.
	SetParamValues(values ...string)

	// QueryParam returns the query param for the provided name.
	QueryParam(name string) string

	// QueryParams returns the query parameters as `url.Values`.
	QueryParams() url.Values

	// QueryString returns the URL query string.
	QueryString() string

	// FormValue returns the form field value for the provided name.
	FormValue(name string) string

	// FormParams returns the form parameters as `url.Values`.
	FormParams() (url.Values, error)

	// FormFile returns the multipart form file for the provided name.
	FormFile(name string) (*multipart.FileHeader, error)

	// MultipartForm returns the multipart form.
	MultipartForm() (*multipart.Form, error)

	// Cookie returns the named cookie provided in the request.
	Cookie(name string) (*http.Cookie, error)

	// SetCookie adds a `Set-Cookie` header in HTTP response.
	SetCookie(cookie *http.Cookie)

	// Cookies returns the HTTP cookies sent with the request.
	Cookies() []*http.Cookie

	// Get retrieves data from the context.
	Get(key string) interface{}

	// Set saves data in the context.
	Set(key string, val interface{})

	// Bind binds the request body into provided type `i`. The default binder
	// does it based on Content-Type header.
	Bind(i interface{}) error

	// Validate validates provided `i`. It is usually called after `Context#Bind()`.
	// Validator must be registered using `Application#Validator`.
	Validate(i interface{}) error

	// Render renders a template with data and sends a text/html response with status
	// code. Renderer must be registered using `Application.Renderer`.
	Render(code int, name string, data interface{}) error

	// HTML sends an HTTP response with status code.
	HTML(code int, html string) error

	// HTMLBlob sends an HTTP blob response with status code.
	HTMLBlob(code int, b []byte) error

	// String sends a string response with status code.
	String(code int, s string) error

	// JSON sends a JSON response with status code.
	JSON(code int, i interface{}) error

	// JSONPretty sends a pretty-print JSON with status code.
	JSONPretty(code int, i interface{}, indent string) error

	// JSONBlob sends a JSON blob response with status code.
	JSONBlob(code int, b []byte) error

	// JSONP sends a JSONP response with status code. It uses `callback` to construct
	// the JSONP payload.
	JSONP(code int, callback string, i interface{}) error

	// JSONPBlob sends a JSONP blob response with status code. It uses `callback`
	// to construct the JSONP payload.
	JSONPBlob(code int, callback string, b []byte) error

	// XML sends an XML response with status code.
	XML(code int, i interface{}) error

	// XMLPretty sends a pretty-print XML with status code.
	XMLPretty(code int, i interface{}, indent string) error

	// XMLBlob sends an XML blob response with status code.
	XMLBlob(code int, b []byte) error

	// Blob sends a blob response with status code and content type.
	Blob(code int, contentType string, b []byte) error

	// Stream sends a streaming response with status code and content type.
	Stream(code int, contentType string, r io.Reader) error

	// File sends a response with the content of the file.
	File(file string) error

	// Attachment sends a response as attachment, prompting client to save the
	// file.
	Attachment(file string, name string) error

	// Inline sends a response as inline, opening the file in the browser.
	Inline(file string, name string) error

	// NoContent sends a response with no body and a status code.
	NoContent(code int) error

	// Redirect redirects the request to a provided URL with status code.
	Redirect(code int, url string) error

	// Error invokes the registered HTTP error handler. Generally used by middleware.
	Error(err error)

	// Handler returns the matched handler by router.
	Handler() HandlerFunc

	// SetHandler sets the matched handler by router.
	SetHandler(h HandlerFunc)

	// Logger returns the `Logger` instance.
	Logger() Logger

	// Set the logger
	SetLogger(l Logger)

	// Application returns the `Application` instance.
	Application() *Application

	// Reset resets the context after request completes. It must be called along
	// with `Application#AcquireContext()` and `Application#ReleaseContext()`.
	// See `Application#ServeHTTP()`
	Reset(r *http.Request, w http.ResponseWriter)
}

Context represents the context of the current HTTP request. It holds request and response objects, path, path parameters, data and registered handler.

type DefaultBinder

type DefaultBinder struct{}

DefaultBinder is the default implementation of the Binder interface.

func (*DefaultBinder) Bind

func (b *DefaultBinder) Bind(i interface{}, c Context) (err error)

Bind implements the `Binder#Bind` function.

type Group

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

Group is a set of sub-routes for a specified route. It can be used for inner routes that share a common middleware or functionality that should be separate from the parent echo instance while still inheriting from it.

func (*Group) Add

func (g *Group) Add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

Add implements `Application#Add()` for sub-routes within the Group.

func (*Group) AddMiddleware

func (g *Group) AddMiddleware(key string, middleware MiddlewareFunc)

func (*Group) Any

func (g *Group) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc) []*Route

Any implements `Application#Any()` for sub-routes within the Group.

func (*Group) CONNECT

func (g *Group) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

CONNECT implements `Application#CONNECT()` for sub-routes within the Group.

func (*Group) DELETE

func (g *Group) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

DELETE implements `Application#DELETE()` for sub-routes within the Group.

func (*Group) File

func (g *Group) File(path, file string)

File implements `Application#File()` for sub-routes within the Group.

func (*Group) GET

func (g *Group) GET(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

GET implements `Application#GET()` for sub-routes within the Group.

func (*Group) Group

func (g *Group) Group(prefix string, middleware ...MiddlewareFunc) (sg *Group)

Group creates a new sub-group with prefix and optional sub-group-level middleware.

func (*Group) HEAD

func (g *Group) HEAD(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

HEAD implements `Application#HEAD()` for sub-routes within the Group.

func (*Group) Match

func (g *Group) Match(methods []string, path string, handler HandlerFunc, middleware ...MiddlewareFunc) []*Route

Match implements `Application#Match()` for sub-routes within the Group.

func (*Group) OPTIONS

func (g *Group) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

OPTIONS implements `Application#OPTIONS()` for sub-routes within the Group.

func (*Group) PATCH

func (g *Group) PATCH(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

PATCH implements `Application#PATCH()` for sub-routes within the Group.

func (*Group) POST

func (g *Group) POST(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

POST implements `Application#POST()` for sub-routes within the Group.

func (*Group) PUT

func (g *Group) PUT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

PUT implements `Application#PUT()` for sub-routes within the Group.

func (*Group) Remove

func (g *Group) Remove(key string)

func (*Group) Static

func (g *Group) Static(prefix, root string)

Static implements `Application#Static()` for sub-routes within the Group.

func (*Group) TRACE

func (g *Group) TRACE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

TRACE implements `Application#TRACE()` for sub-routes within the Group.

func (*Group) Use

func (g *Group) Use(middleware ...MiddlewareFunc)

Use implements `Application#Use()` for sub-routes within the Group.

type GzLambda

type GzLambda struct {
	core.RequestAccessor
	// contains filtered or unexported fields
}

GzLambda makes it easy to send API Gateway proxy events to a gz.Application. The library transforms the proxy event into an HTTP request and then creates a proxy response object from the http.ResponseWriter

func New

func New(app *Application) *GzLambda

New creates a new instance of the GzLambda object. Receives an initialized *gz.Application object - normally created with gz.Initialize(nil). It returns the initialized instance of the GzLambda object.

func (*GzLambda) Proxy

Proxy receives an API Gateway proxy event, transforms it into an http.Request object, and sends it to the gz.Application for routing. It returns a proxy response object generated from the http.ResponseWriter.

func (*GzLambda) ProxyWithContext

ProxyWithContext receives context and an API Gateway proxy event, transforms them into an http.Request object, and sends it to the gz.Application for routing. It returns a proxy response object generated from the http.ResponseWriter.

type HTTPError

type HTTPError struct {
	Code    int         `json:"-"`
	Message interface{} `json:"message"`
	// 存储外部依赖项返回的错误
	Internal error `json:"-"` // Stores the error returned by an external dependency
}

HTTPError represents an error that occurred while handling a request. HTTPError表示在处理请求时发生的错误。

func NewHTTPError

func NewHTTPError(code int, message ...interface{}) *HTTPError

NewHTTPError creates a new HTTPError instance.

func (*HTTPError) Error

func (he *HTTPError) Error() string

Error makes it compatible with `error` interface.

func (*HTTPError) SetInternal

func (he *HTTPError) SetInternal(err error) *HTTPError

SetInternal sets error to HTTPError.Internal

func (*HTTPError) Unwrap

func (he *HTTPError) Unwrap() error

Unwrap satisfies the Go 1.13 error wrapper interface.

type HTTPErrorHandler

type HTTPErrorHandler func(error, Context)

HTTPErrorHandler is a centralized HTTP error handler. HTTPErrorHandler是集中式HTTP错误处理程序。

type HandlerFunc

type HandlerFunc func(Context) error

HandlerFunc defines a function to serve HTTP requests. HandlerFunc定义了一个服务于HTTP请求的函数。

func WrapHandler

func WrapHandler(h http.Handler) HandlerFunc

WrapHandler wraps `http.Handler` into `gz.HandlerFunc`.

type IPExtractor

type IPExtractor func(*http.Request) string

IPExtractor is a function to extract IP addr from http.Request. Set appropriate one to Application#IPExtractor. See https://gz.labstack.com/guide/ip-address for more details.

func ExtractIPDirect

func ExtractIPDirect() IPExtractor

ExtractIPDirect extracts IP address using actual IP address. Use this if your server faces to internet directory (i.e.: uses no proxy).

func ExtractIPFromRealIPHeader

func ExtractIPFromRealIPHeader(options ...TrustOption) IPExtractor

ExtractIPFromRealIPHeader extracts IP address using x-real-ip header. Use this if you put proxy which uses this header.

func ExtractIPFromXFFHeader

func ExtractIPFromXFFHeader(options ...TrustOption) IPExtractor

ExtractIPFromXFFHeader extracts IP address using x-forwarded-for header. Use this if you put proxy which uses this header. This returns nearest untrustable IP. If all IPs are trustable, returns furthest one (i.e.: XFF[0]).

type Logger

type Logger interface {
	Output() io.Writer
	SetOutput(w io.Writer)
	Prefix() string
	SetPrefix(p string)
	Level() log.Lvl
	SetLevel(v log.Lvl)
	SetHeader(h string)
	Print(i ...interface{})
	Printf(format string, args ...interface{})
	Printj(j log.JSON)
	Debug(i ...interface{})
	Debugf(format string, args ...interface{})
	Debugj(j log.JSON)
	Info(i ...interface{})
	Infof(format string, args ...interface{})
	Infoj(j log.JSON)
	Warn(i ...interface{})
	Warnf(format string, args ...interface{})
	Warnj(j log.JSON)
	Error(i ...interface{})
	Errorf(format string, args ...interface{})
	Errorj(j log.JSON)
	Fatal(i ...interface{})
	Fatalj(j log.JSON)
	Fatalf(format string, args ...interface{})
	Panic(i ...interface{})
	Panicj(j log.JSON)
	Panicf(format string, args ...interface{})
}

Logger defines the logging interface.

type Map

type Map map[string]interface{}

Map defines a generic map of type `map[string]interface{}`.

type MiddlewareFunc

type MiddlewareFunc func(HandlerFunc) HandlerFunc

MiddlewareFunc defines a function to process middleware. MiddlewareFunc定义了处理中间件的功能。

func WrapMiddleware

func WrapMiddleware(m func(http.Handler) http.Handler) MiddlewareFunc

WrapMiddleware wraps `func(http.Handler) http.Handler` into `gz.MiddlewareFunc`

type Renderer

type Renderer interface {
	Render(io.Writer, string, interface{}, Context) error
}

Renderer is the interface that wraps the Render function. Renderer是包装Render函数的接口。

type Response

type Response struct {
	Writer http.ResponseWriter
	//// 添加 http.Response
	//HttpResponse http.Response
	Status    int
	Size      int64
	Committed bool
	// contains filtered or unexported fields
}

Response wraps an http.ResponseWriter and implements its interface to be used by an HTTP handler to construct an HTTP response. See: https://golang.org/pkg/net/http/#ResponseWriter

func NewResponse

func NewResponse(w http.ResponseWriter, a *Application) (r *Response)

NewResponse creates a new instance of Response.

func (*Response) After

func (r *Response) After(fn func())

After registers a function which is called just after the response is written. If the `Content-Length` is unknown, none of the after function is executed.

func (*Response) Before

func (r *Response) Before(fn func())

Before registers a function which is called just before the response is written.

func (*Response) Flush

func (r *Response) Flush()

Flush implements the http.Flusher interface to allow an HTTP handler to flush buffered data to the client. See http.Flusher(https://golang.org/pkg/net/http/#Flusher)

func (*Response) Header

func (r *Response) Header() http.Header

Header returns the header map for the writer that will be sent by WriteHeader. Changing the header after a call to WriteHeader (or Write) has no effect unless the modified headers were declared as trailers by setting the "Trailer" header before the call to WriteHeader (see example) To suppress implicit response headers, set their value to nil. Example: https://golang.org/pkg/net/http/#example_ResponseWriter_trailers

func (*Response) Hijack

func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack implements the http.Hijacker interface to allow an HTTP handler to take over the connection. See http.Hijacker(https://golang.org/pkg/net/http/#Hijacker)

func (*Response) Write

func (r *Response) Write(b []byte) (n int, err error)

Write writes the data to the connection as part of an HTTP reply.

func (*Response) WriteHeader

func (r *Response) WriteHeader(code int)

WriteHeader sends an HTTP response header with status code. If WriteHeader is not called explicitly, the first call to Write will trigger an implicit WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly used to send error codes.

type Route

type Route struct {
	Method string `json:"method"`
	Path   string `json:"path"`
	Name   string `json:"name"`
}

Route contains a handler and information for matching against requests.

type Router

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

Router is the registry of all registered routes for an `Application` instance for request matching and URL path parameter parsing.

func NewRouter

func NewRouter(a *Application) *Router

NewRouter returns a new Router instance.

func (*Router) Add

func (r *Router) Add(method, path string, h HandlerFunc)

Add registers a new route for method and path with matching handler.

func (*Router) Find

func (r *Router) Find(method, path string, c Context)

Find lookup a handler registered for method and path. It also parses URL for path parameters and load them into context.

For performance:

- Get context from `Application#AcquireContext()` - Reset it `Context#Reset()` - Return it `Application#ReleaseContext()`.

type TrustOption

type TrustOption func(*ipChecker)

TrustOption is config for which IP address to trust

func TrustIPRange

func TrustIPRange(ipRange *net.IPNet) TrustOption

TrustIPRange add trustable IP ranges using CIDR notation.

func TrustLinkLocal

func TrustLinkLocal(v bool) TrustOption

TrustLinkLocal configures if you trust link-local address (default: true).

func TrustLoopback

func TrustLoopback(v bool) TrustOption

TrustLoopback configures if you trust loopback address (default: true).

func TrustPrivateNet

func TrustPrivateNet(v bool) TrustOption

TrustPrivateNet configures if you trust private network address (default: true).

type Validator

type Validator interface {
	Validate(i interface{}) error
}

Validator is the interface that wraps the Validate function. 验证程序是包装Validate函数的接口。

Directories

Path Synopsis
scf_proxy
core
Package core provides utility methods that help convert proxy events into an http.Request and http.ResponseWriter Package core provides utility methods that help convert proxy events into an http.Request and http.ResponseWriter
Package core provides utility methods that help convert proxy events into an http.Request and http.ResponseWriter Package core provides utility methods that help convert proxy events into an http.Request and http.ResponseWriter

Jump to

Keyboard shortcuts

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