gin

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

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

Go to latest
Published: May 31, 2016 License: MIT Imports: 27 Imported by: 0

README

Gin Web Framework

Gin is a web framework written in Golang. It features a martini-like API with much better performance, up to 40 times faster thanks to httprouter. If you need performance and good productivity, you will love Gin.

Start using it

  1. Download and install it:
go get -u github.com/chanxuehong/gin
  1. Import it in your code:
import "github.com/chanxuehong/gin"

API Examples

Using GET, POST, PUT, PATCH, DELETE and OPTIONS
package main

import (
	"github.com/chanxuehong/gin"
)

func handler(ctx *gin.Context) {
	ctx.String(200, ctx.Request.Method)
}

func main() {
	router := gin.New()

	router.Get("/get", handler)
	router.Post("/post", handler)
	router.Put("/put", handler)
	router.Delete("/delete", handler)
	router.Patch("/patch", handler)
	router.Head("/head", handler)
	router.Options("/options", handler)

	// Listen and server on 0.0.0.0:8080
	router.Run(":8080")
}
package main

import (
	"github.com/chanxuehong/gin"
	"github.com/chanxuehong/gin/middleware"
)

func handler(ctx *gin.Context) {
	ctx.String(200, ctx.Request.Method)
}

func main() {
	router := gin.New()
	router.Use(middleware.Logger(), middleware.Recovery()) // use middleware

	router.Get("/get", handler)
	router.Post("/post", handler)
	router.Put("/put", handler)
	router.Delete("/delete", handler)
	router.Patch("/patch", handler)
	router.Head("/head", handler)
	router.Options("/options", handler)

	// Listen and server on 0.0.0.0:8080
	router.Run(":8080")
}
Parameters in path
package main

import (
	"net/http"

	"github.com/chanxuehong/gin"
)

func main() {
	router := gin.New()

	// This handler will match /user/john but will not match neither /user/ or /user
	router.Get("/user/:name", func(ctx *gin.Context) {
		name := ctx.Param("name")
		ctx.String(http.StatusOK, "Hello %s", name)
	})

	// However, this one will match /user/john/ and also /user/john/send
	// If no other routers match /user/john, it will redirect to /user/join/
	router.Get("/user/:name/*action", func(ctx *gin.Context) {
		name := ctx.Param("name")
		action := ctx.Param("action")
		message := name + " is " + action
		ctx.String(http.StatusOK, message)
	})

	router.Run(":8080")
}
Querystring parameters
package main

import (
	"net/http"

	"github.com/chanxuehong/gin"
)

func main() {
	router := gin.New()

	// Query string parameters are parsed using the existing underlying request object.
	// The request responds to a url matching:  /welcome?firstname=Jane&lastname=Doe
	router.Get("/welcome", func(ctx *gin.Context) {
		firstname := ctx.DefaultQuery("firstname", "Guest")
		lastname := ctx.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")

		ctx.String(http.StatusOK, "Hello %s %s", firstname, lastname)
	})

	router.Run(":8080")
}
Urlencoded Form
package main

import (
	"github.com/chanxuehong/gin"
)

func main() {
	router := gin.New()

	router.Post("/form_post", func(ctx *gin.Context) {
		message := ctx.PostFormValue("message")
		nick := ctx.DefaultPostFormValue("nick", "anonymous")

		ctx.JSON(200, gin.H{
			"status":  "posted",
			"message": message,
			"nick":    nick,
		})
	})

	router.Run(":8080")
}
Another example: query + post form
POST /post?id=1234&page=1 HTTP/1.1
Content-Type: application/x-www-form-urlencoded

name=manu&message=this_is_great
package main

import (
	"fmt"

	"github.com/chanxuehong/gin"
)

func main() {
	router := gin.New()

	router.Post("/post", func(c *gin.Context) {
		id := c.Query("id")
		page := c.DefaultQuery("id", "0")
		name := c.PostFormValue("name")
		message := c.PostFormValue("message")

		fmt.Println("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
	})

	router.Run(":8080")
}
id: 1234; page: 0; name: manu; message: this_is_great
Grouping routes
package main

import (
	"github.com/chanxuehong/gin"
)

func handler1(ctx *gin.Context) { ctx.ResponseWriter.WriteString("1") }
func handler2(ctx *gin.Context) { ctx.ResponseWriter.WriteString("2") }
func handler3(ctx *gin.Context) { ctx.ResponseWriter.WriteString("3") }
func handler4(ctx *gin.Context) { ctx.ResponseWriter.WriteString("4") }
func handler5(ctx *gin.Context) { ctx.ResponseWriter.WriteString("5") }
func handler6(ctx *gin.Context) { ctx.ResponseWriter.WriteString("6") }

func main() {
	router := gin.New()

	// Simple group: v1
	v1 := router.Group("/v1")
	{
		v1.Get("/login", handler1)
		v1.Get("/submit", handler2)
		v1.Get("/read", handler3)
	}

	// Simple group: v2
	v2 := router.Group("/v2")
	{
		v2.Get("/login", handler4)
		v2.Get("/submit", handler5)
		v2.Get("/read", handler6)
	}

	router.Run(":8080")
}
creating and using middleware
package main

import (
	"github.com/chanxuehong/gin"
)

func middleware1(ctx *gin.Context) {
	ctx.ResponseWriter.WriteString("middleware1\r\n")
}
func middleware21(ctx *gin.Context) {
	ctx.ResponseWriter.WriteString("middleware21\r\n")
}
func middleware22(ctx *gin.Context) {
	ctx.ResponseWriter.WriteString("middleware22\r\n")
}
func handler1(ctx *gin.Context) {
	ctx.ResponseWriter.WriteString("handler1\r\n")
}
func handler2(ctx *gin.Context) {
	ctx.ResponseWriter.WriteString("handler2\r\n")
}

func groupMiddleware1(ctx *gin.Context) {
	ctx.ResponseWriter.WriteString("group middleware1\r\n")
}
func groupMiddleware2(ctx *gin.Context) {
	ctx.ResponseWriter.WriteString("group middleware2\r\n")
}
func groupMiddleware31(ctx *gin.Context) {
	ctx.ResponseWriter.WriteString("group middleware31\r\n")
}
func groupMiddleware32(ctx *gin.Context) {
	ctx.ResponseWriter.WriteString("group middleware32\r\n")
}
func groupHandler1(ctx *gin.Context) {
	ctx.ResponseWriter.WriteString("group handler1\r\n")
}
func groupHandler2(ctx *gin.Context) {
	ctx.ResponseWriter.WriteString("group handler2\r\n")
}

func main() {
	// Creates a router without any middleware by default
	r := gin.New()

	// Global middleware
	r.Use(middleware1)

	// Per route middleware, you can add as many as you desire.
	r.Get("/test1", middleware21, handler1)
	r.Get("/test2", middleware22, handler2)

	group := r.Group("/user", groupMiddleware1) // group middleware
	group.Use(groupMiddleware2)                 // group middleware

	// Per route middleware, you can add as many as you desire.
	group.Get("/test1", groupMiddleware31, groupHandler1)
	group.Get("/test2", groupMiddleware32, groupHandler2)

	// Listen and server on 0.0.0.0:8080
	r.Run(":8080")
}
Model binding and validation

To bind a request body into a type, use model binding. We currently support binding of JSON, XML.

Note that you need to set the corresponding binding tag on all fields you want to bind. For example, when binding from JSON, set json:"fieldname".

You can also specify that specific fields are required. If a field is decorated with validate:"required" and has a empty value when binding, the current request will fail with an error.

package main

import (
	"net/http"

	"github.com/chanxuehong/gin"
)

// Binding from JSON
type Login struct {
	User     string `json:"user"     validate:"required"`
	Password string `json:"password" validate:"required"`
}

func main() {
	router := gin.New()
	router.DefaultValidator(gin.DefaultValidator) // it not set, it does not validate the struct.

	// Example for binding JSON ({"user": "manu", "password": "123"})
	router.Post("/loginJSON", func(ctx *gin.Context) {
		var json Login
		if ctx.BindJSON(&json) == nil {
			if json.User == "manu" && json.Password == "123" {
				ctx.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
			} else {
				ctx.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
			}
		}
	})

	// Listen and server on 0.0.0.0:8080
	router.Run(":8080")
}
XML and JSON rendering
package main

import (
	"net/http"

	"github.com/chanxuehong/gin"
)

func main() {
	r := gin.New()

	// gin.H is a shortcut for map[string]interface{}
	r.Get("/someJSON", func(ctx *gin.Context) {
		ctx.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
	})

	r.Get("/moreJSON", func(ctx *gin.Context) {
		// You also can use a struct
		var msg struct {
			Name    string `json:"user"`
			Message string
			Number  int
		}
		msg.Name = "Lena"
		msg.Message = "hey"
		msg.Number = 123
		// Note that msg.Name becomes "user" in the JSON
		// Will output  :   {"user": "Lena", "Message": "hey", "Number": 123}
		ctx.JSON(http.StatusOK, msg)
	})

	r.Get("/someXML", func(ctx *gin.Context) {
		ctx.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
	})

	// Listen and server on 0.0.0.0:8080
	r.Run(":8080")
}
Serving static files
package main

import (
	"net/http"

	"github.com/chanxuehong/gin"
)

func main() {
	router := gin.New()

	router.StaticAlias("/assets/", gin.Dir("./assets/"))  // /assets/1234.jpg --> ./assets/1234.jpg
	router.StaticRoot("/more_static/", http.Dir("/root")) // /more_static/1234.jpg --> /root/more_static/1234.jpg
	router.StaticFile("/favicon.ico", "./resources/favicon.ico")

	// Listen and server on 0.0.0.0:8080
	router.Run(":8080")
}
Redirects

Issuing a HTTP redirect is easy:

package main

import (
	"net/http"

	"github.com/chanxuehong/gin"
)

func main() {
	router := gin.New()

	router.Get("/test", func(ctx *gin.Context) {
		ctx.Redirect(http.StatusMovedPermanently, "http://www.google.com/")
	})

	// Listen and server on 0.0.0.0:8080
	router.Run(":8080")
}

Both internal and external locations are supported.

goroutines inside a middleware

When starting inside a middleware or handler, you SHOULD NOT use the original context inside it, you have to use a read-only copy.

package main

import (
	"log"
	"time"

	"github.com/chanxuehong/gin"
)

func main() {
	r := gin.New()

	r.Get("/long_async", func(ctx *gin.Context) {
		// create copy to be used inside the goroutine
		ctxCopy := ctx.Copy()
		go func() {
			// simulate a long task with time.Sleep(). 5 seconds
			time.Sleep(5 * time.Second)

			// note than you are using the copied context "ctxCopy", IMPORTANT
			log.Println("Done! in path " + ctxCopy.Request.URL.Path)
		}()
	})

	r.Get("/long_sync", func(ctx *gin.Context) {
		// simulate a long task with time.Sleep(). 5 seconds
		time.Sleep(5 * time.Second)

		// since we are NOT using a goroutine, we do not have to copy the context
		log.Println("Done! in path " + ctx.Request.URL.Path)
	})

	// Listen and server on 0.0.0.0:8080
	r.Run(":8080")
}
Custom HTTP configuration

Use http.ListenAndServe() directly, like this:

package main

import (
	"net/http"

	"github.com/chanxuehong/gin"
)

func main() {
	router := gin.New()
	http.ListenAndServe(":8080", router)
}

or

package main

import (
	"net/http"
	"time"

	"github.com/chanxuehong/gin"
)

func main() {
	router := gin.New()

	s := &http.Server{
		Addr:           ":8080",
		Handler:        router,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	s.ListenAndServe()
}

Documentation

Index

Constants

View Source
const (
	HTTPMethodGet     = http.MethodGet
	HTTPMethodHead    = http.MethodHead
	HTTPMethodPost    = http.MethodPost
	HTTPMethodPut     = http.MethodPut
	HTTPMethodPatch   = http.MethodPatch
	HTTPMethodDelete  = http.MethodDelete
	HTTPMethodConnect = http.MethodConnect
	HTTPMethodOptions = http.MethodOptions
	HTTPMethodTrace   = http.MethodTrace
)

Common HTTP methods.

Unless otherwise noted, these are defined in RFC 7231 section 4.3.

View Source
const (
	MIMEApplicationURLEncodedForm = "application/x-www-form-urlencoded"
	MIMEMultipartForm             = "multipart/form-data"
	MIMEApplicationOctetStream    = "application/octet-stream"
	MIMEApplicationProtobuf       = "application/protobuf"

	MIMEApplicationJSON       = "application/json"
	MIMEApplicationXML        = "application/xml"
	MIMEApplicationJavaScript = "application/javascript"
	MIMETextPlain             = "text/plain"
	MIMETextHTML              = "text/html"
	MIMETextXML               = "text/xml"

	MIMEApplicationJSONCharsetUTF8       = MIMEApplicationJSON + "; charset=utf-8"
	MIMEApplicationXMLCharsetUTF8        = MIMEApplicationXML + "; charset=utf-8"
	MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; charset=utf-8"
	MIMETextPlainCharsetUTF8             = MIMETextPlain + "; charset=utf-8"
	MIMETextHTMLCharsetUTF8              = MIMETextHTML + "; charset=utf-8"
	MIMETextXMLCharsetUTF8               = MIMETextXML + "; charset=utf-8"
)

MIME types

View Source
const (
	HeaderAcceptEncoding                = "Accept-Encoding"
	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"
	HeaderXForwardedProto               = "X-Forwarded-Proto"
	HeaderXHTTPMethodOverride           = "X-HTTP-Method-Override"
	HeaderXForwardedFor                 = "X-Forwarded-For"
	HeaderXRealIP                       = "X-Real-IP"
	HeaderServer                        = "Server"
	HeaderOrigin                        = "Origin"
	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"
	HeaderXCSRFToken              = "X-CSRF-Token"
)

Headers

Variables

This section is empty.

Functions

This section is empty.

Types

type Context

type Context struct {
	ResponseWriter ResponseWriter // convert from Context.responseWriter2
	Request        *http.Request

	PathParams Params

	// Validator will validate object when binding if not nil.
	// By default the Validator is nil, you can set default Validator using
	//     Engine.DefaultValidator()
	// also you can change this in handlers.
	Validator StructValidator
	// contains filtered or unexported fields
}

Context is the most important part of gin. It allows us to pass variables between middleware, manage the flow, validate the JSON of a request and render a JSON response for example.

NOTE:
Context and the ResponseWriter, PathParams fields of Context
can NOT be safely used outside the request's scope, see Context.Copy().

func (*Context) Abort

func (ctx *Context) Abort()

Abort prevents pending handlers from being called. Note that this will not stop the current handler. Let's say you have an authorization middleware that validates that the current request is authorized. If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers for this request are not called.

func (*Context) AbortWithError

func (ctx *Context) AbortWithError(code int, format string, values ...interface{})

AbortWithError writes the status code and error message to response, then stops the chain. The error message should be plain text. This method calls `String()` internally, see Context.String() for more details.

func (*Context) AbortWithStatus

func (ctx *Context) AbortWithStatus(code int)

AbortWithStatus writes the headers with the specified status code and calls `Abort()`. For example, a failed attempt to authentificate a request could use: context.AbortWithStatus(401).

func (*Context) Attachment

func (ctx *Context) Attachment(content io.Reader, filename string) (err error)

Attachment adds a `Content-Disposition:attachment;filename="XXX"` header and writes the specified content into the body stream.

func (*Context) AttachmentFile

func (ctx *Context) AttachmentFile(filepath, filename string) (err error)

AttachmentFile adds a `Content-Disposition:attachment;filename="XXX"` header and writes the specified file into the body stream.

filename can be empty, in that case name of the file is used.

func (*Context) BindJSON

func (ctx *Context) BindJSON(obj interface{}) (err error)

BindJSON is a shortcut for ctx.BindWith(obj, binder.JSON).

func (*Context) BindWith

func (ctx *Context) BindWith(obj interface{}, b binder.Binder) (err error)

BindWith binds the passed struct pointer using the specified Binder.

func (*Context) BindXML

func (ctx *Context) BindXML(obj interface{}) (err error)

BindXML is a shortcut for ctx.BindWith(obj, binder.XML).

func (*Context) ClientIP

func (ctx *Context) ClientIP() (ip string)

func (*Context) Cookie

func (ctx *Context) Cookie(name string) (*http.Cookie, error)

Cookie is a shortcut for ctx.Request.Cookie(name). It returns the named cookie provided in the request or http.ErrNoCookie if not found.

func (*Context) Copy

func (ctx *Context) Copy() *Context

Copy returns a copy of the current context that can be safely used outside the request's scope. This have to be used when the context has to be passed to a goroutine.

func (*Context) DefaultFormValue

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

DefaultFormValue like FormValue if name matched, otherwise it returns defaultValue.

func (*Context) DefaultPostFormValue

func (ctx *Context) DefaultPostFormValue(name, defaultValue string) (value string)

DefaultPostFormValue like PostFormValue if name matched, otherwise it returns defaultValue.

func (*Context) DefaultQuery

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

DefaultQuery like Query if name matched, otherwise it returns defaultValue.

func (*Context) Delete

func (ctx *Context) Delete(key string)

Delete remove the value with given key.

func (*Context) FormValue

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

FormValue is a shortcut for ctx.Request.FormValue(name).

func (*Context) Get

func (ctx *Context) Get(key string) (value interface{}, exists bool)

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

func (*Context) HandlerName

func (ctx *Context) HandlerName() string

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

func (*Context) IsAborted

func (ctx *Context) IsAborted() bool

IsAborted returns true if the currect context was aborted.

func (*Context) JSON

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

JSON sends a JSON response with status code. It sets the Content-Type as "application/json; charset=utf-8".

func (*Context) JSONBlob

func (ctx *Context) JSONBlob(code int, blob []byte) (err error)

JSONBlob sends a JSON response with status code. It sets the Content-Type as "application/json; charset=utf-8".

func (*Context) JSONIndent

func (ctx *Context) JSONIndent(code int, obj interface{}, prefix string, indent string) (err error)

JSONIndent sends a JSON response with status code, but it applies prefix and indent to format the output. It sets the Content-Type as "application/json; charset=utf-8".

func (*Context) MustGet

func (ctx *Context) MustGet(key string) interface{}

MustGet returns the value for the given key if it exists, otherwise it panics.

func (*Context) Next

func (ctx *Context) Next()

Next should be used only inside middleware. It executes the pending handlers in the chain inside the calling handler.

func (*Context) NoContent

func (ctx *Context) NoContent(code int) error

NoContent sends a response with no body and a status code.

func (*Context) Param

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

Param is a shortcut for ctx.PathParams.ByName(name).

func (*Context) ParamByIndex

func (ctx *Context) ParamByIndex(index int) string

ParamByIndex is a shortcut for ctx.PathParams.ByIndex(index).

func (*Context) PostFormValue

func (ctx *Context) PostFormValue(name string) (value string)

PostFormValue is a shortcut for ctx.Request.PostFormValue(name).

func (*Context) Query

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

Query returns the url query value by name.

func (*Context) QueryParams

func (ctx *Context) QueryParams() url.Values

QueryParams returns the url query values.

func (*Context) Redirect

func (ctx *Context) Redirect(code int, location string)

Redirect redirects the request using http.Redirect with status code.

func (*Context) ServeContent

func (ctx *Context) ServeContent(content io.ReadSeeker, name string, modtime time.Time) (err error)

ServeContent is wrapper for http.ServeContent.

func (*Context) ServeFile

func (ctx *Context) ServeFile(filepath string) (err error)

ServeFile is wrapper for http.ServeFile.

func (*Context) Set

func (ctx *Context) Set(key string, value interface{})

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

func (*Context) SetCookie

func (ctx *Context) SetCookie(cookie *http.Cookie)

SetCookie is a shortcut for http.SetCookie(ctx.ResponseWriter, cookie).

func (*Context) String

func (ctx *Context) String(code int, format string, values ...interface{}) (err error)

String writes the given string into the response body. It sets the Content-Type as "text/plain; charset=utf-8".

func (*Context) XML

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

XML sends an XML response with status code. It sets the Content-Type as "application/xml; charset=utf-8".

func (*Context) XMLBlob

func (ctx *Context) XMLBlob(code int, blob []byte) (err error)

XMLBlob sends an XML response with status code. It sets the Content-Type as "application/xml; charset=utf-8".

func (*Context) XMLIndent

func (ctx *Context) XMLIndent(code int, obj interface{}, prefix string, indent string) (err error)

XMLIndent sends an XML response with status code, but it applies prefix and indent to format the output. It sets the Content-Type as "application/xml; charset=utf-8".

type Dir

type Dir string

Dir like http.Dir but the http.File returned by Dir.Open() does not list the directory files, so we can pass Dir to http.FileServer() to prevent it lists the directory files.

func (Dir) Open

func (d Dir) Open(name string) (http.File, error)

type Engine

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

Engine is the framework's instance, it contains the muxer, middleware and configuration settings. Create an instance of Engine, by using New() or Default().

NOTE:
Engine is NOT copyable.
Please serially sets Engine(normally in 'init' or 'main' goroutine).

func New

func New() *Engine

New returns a new blank Engine instance without any middleware attached. By default the configuration is: - RedirectTrailingSlash: true - RedirectFixedPath: false - HandleMethodNotAllowed: false

func (*Engine) DebugPProf

func (engine *Engine) DebugPProf(middleware ...HandlerFunc)

DebugPProf registers internal HandlerFunc to process path "/debug/pprof/*name", for more information please see net/http/pprof.

Please NOTE that DebugPProf does not use any middleware of Engine, you can specify middlewares optionally when you call this method.

func (*Engine) DefaultValidator

func (engine *Engine) DefaultValidator(v StructValidator)

DefaultValidator sets the default Validator to validate object when binding.

func (*Engine) FetchClientIPFromHeader

func (engine *Engine) FetchClientIPFromHeader(b bool)

If enabled, the engine get client IP from http hearder X-Real-IP, X-Forwarded-For.

Default is false.

func (*Engine) HandleMethodNotAllowed

func (engine *Engine) HandleMethodNotAllowed(b bool)

If enabled, the router checks if another method is allowed for the current route, if the current request can not be routed. If this is the case, the request is answered with 'Method Not Allowed' and HTTP status code 405. If no other Method is allowed, the request is delegated to the NotFound handler.

Default is false.

func (*Engine) NoMethod

func (engine *Engine) NoMethod(handlers ...HandlerFunc)

NoMethod set handlers for NoMethod. It return a 405 code by default. Engine.NoMethod() removes all no-method handlers.

func (*Engine) NoRoute

func (engine *Engine) NoRoute(handlers ...HandlerFunc)

NoRoute set handlers for NoRoute. It return a 404 code by default. Engine.NoRoute() removes all no-route handlers.

func (*Engine) RedirectFixedPath

func (engine *Engine) RedirectFixedPath(b bool)

If enabled, the router tries to fix the current request path, if no handle is registered for it. First superfluous path elements like ../ or // are removed. Afterwards the router does a case-insensitive lookup of the cleaned path. If a handle can be found for this route, the router makes a redirection to the corrected path with status code 301 for GET requests and 307 for all other request methods. For example /FOO and /..//Foo could be redirected to /foo. RedirectTrailingSlash is independent of this option.

Default is false.

func (*Engine) RedirectTrailingSlash

func (engine *Engine) RedirectTrailingSlash(b bool)

Enables automatic redirection if the current route can't be matched but a handler for the path with (without) the trailing slash exists. For example if /foo/ is requested but a route only exists for /foo, the client is redirected to /foo with http status code 301 for GET requests and 307 for all other request methods.

Default is true.

func (*Engine) Routes

func (engine *Engine) Routes() []Route

Routes returns a slice of registered routes, including some useful information, such as: the http method, path and the handler name.

func (*Engine) Run

func (engine *Engine) Run(addr string) (err error)

Run attaches the engine to a http.Server and starts listening and serving HTTP requests. It is a shortcut for http.ListenAndServe(addr, engine) Note: this method will block the calling goroutine indefinitely unless an error happens.

func (*Engine) RunTLS

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

RunTLS attaches the engine to a http.Server and starts listening and serving HTTPS (secure) requests. It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, engine) Note: this method will block the calling goroutine indefinitely unless an error happens.

func (*Engine) ServeHTTP

func (engine *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface.

func (*Engine) Use

func (engine *Engine) Use(middleware ...HandlerFunc)

Attachs a global middleware to Engine. ie. the middleware attached though Use() will be included in the handler chain for every single request. Even 404, 405, static files... For example, this is the right place for a logger or error management middleware.

type H

type H map[string]interface{}

func (H) MarshalXML

func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) (err error)

MarshalXML implements xml.Marshaler

type HandlerChain

type HandlerChain []HandlerFunc

type HandlerFunc

type HandlerFunc func(*Context)

func WrapHandler

func WrapHandler(h http.Handler) HandlerFunc

func WrapHandlerFunc

func WrapHandlerFunc(fn http.HandlerFunc) HandlerFunc

type Param

type Param struct {
	Key   string
	Value string // May be empty
}

Param is a single URL parameter, consisting of a key and a value.

type Params

type Params []Param

Params is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.

func (Params) ByIndex

func (params Params) ByIndex(index int) string

ByIndex returns the value with given index. If the index out of range, an empty string is returned.

func (Params) ByName

func (params Params) ByName(name string) string

ByName returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

type ResponseWriter

type ResponseWriter response.ResponseWriter
type ResponseWriter interface {
    http.ResponseWriter
    WroteHeader() bool // WroteHeader returns true if header has been written, otherwise false.
    Status() int       // Status returns the response status code of the current request.
    Written() int64    // Written returns number of bytes written in body.
}

type Route

type Route struct {
	Method  string
	Path    string
	Handler string // handler name
}

type RouteGroup

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

RouteGroup is used to configure the internal router, a RouteGroup is associated with a path prefix and an array of middlewares.

NOTE:
Please serially sets RouteGroup(normally in 'init' or 'main' goroutine).

func (*RouteGroup) Any

func (group *RouteGroup) Any(relativePath string, handlers ...HandlerFunc)

Any registers a route that matches all the HTTP methods: GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE.

func (*RouteGroup) BasePath

func (group *RouteGroup) BasePath() string

BasePath returns the path prefix of this RouteGroup.

func (*RouteGroup) Connect

func (group *RouteGroup) Connect(relativePath string, handlers ...HandlerFunc)

Connect is a shortcut for group.Handle("CONNECT", relativePath, handlers)

func (*RouteGroup) Delete

func (group *RouteGroup) Delete(relativePath string, handlers ...HandlerFunc)

Delete is a shortcut for group.Handle("DELETE", relativePath, handlers)

func (*RouteGroup) Get

func (group *RouteGroup) Get(relativePath string, handlers ...HandlerFunc)

Get is a shortcut for group.Handle("GET", relativePath, handlers)

func (*RouteGroup) Group

func (group *RouteGroup) Group(relativePath string, middlewares ...HandlerFunc) *RouteGroup

Group creates a new RouteGroup. You should add all the routes that have common middlewares or the same path prefix. For example, all the routes that use a common middlware for authorization could be grouped.

func (*RouteGroup) Handle

func (group *RouteGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc)

Handle registers a new request handler and middlewares with the given path and method. The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes. See the example code in github.

For GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, CONNECT and TRACE requests the respective shortcut functions can be used.

This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).

func (*RouteGroup) Head

func (group *RouteGroup) Head(relativePath string, handlers ...HandlerFunc)

Head is a shortcut for group.Handle("HEAD", relativePath, handlers)

func (*RouteGroup) Options

func (group *RouteGroup) Options(relativePath string, handlers ...HandlerFunc)

Options is a shortcut for group.Handle("OPTIONS", relativePath, handlers)

func (*RouteGroup) Patch

func (group *RouteGroup) Patch(relativePath string, handlers ...HandlerFunc)

Patch is a shortcut for group.Handle("PATCH", relativePath, handlers)

func (*RouteGroup) Post

func (group *RouteGroup) Post(relativePath string, handlers ...HandlerFunc)

Post is a shortcut for group.Handle("POST", relativePath, handlers)

func (*RouteGroup) Put

func (group *RouteGroup) Put(relativePath string, handlers ...HandlerFunc)

Put is a shortcut for group.Handle("PUT", relativePath, handlers)

func (*RouteGroup) StaticAlias

func (group *RouteGroup) StaticAlias(relativePath string, dir http.FileSystem)

StaticAlias like nginx alias location(also relativePath must be ended with '/' if not empty).

group.StaticAlias("/abc/", http.Dir("/home/root/abc/"))
group.StaticAlias("/abc/", gin.Dir("/home/root/abc/"))

is like this in nginx:

location ^~ /abc/ {
    alias  /home/root/abc/;
}

func (*RouteGroup) StaticFile

func (group *RouteGroup) StaticFile(relativePath, filepath string)

StaticFile registers a single route in order to serve a single file of the local filesystem.

group.StaticFile("favicon.ico", "./resources/favicon.ico")

func (*RouteGroup) StaticRoot

func (group *RouteGroup) StaticRoot(relativePath string, root http.FileSystem)

StaticRoot like nginx root location but relativePath must be ended with '/' if not empty.

group.StaticRoot("/abc/", http.Dir("/home/root"))
group.StaticRoot("/abc/", gin.Dir("/home/root"))

is like this in nginx:

location ^~ /abc/ {
    root   /home/root;
}

func (*RouteGroup) Trace

func (group *RouteGroup) Trace(relativePath string, handlers ...HandlerFunc)

Trace is a shortcut for group.Handle("TRACE", relativePath, handlers)

func (*RouteGroup) Use

func (group *RouteGroup) Use(middlewares ...HandlerFunc)

Use adds middlewares to the group.

type StructValidator

type StructValidator interface {
	// ValidateStruct can receive any kind of type and it should never panic, even if the obj is not right.
	// If the received type is not a struct, any validation should be skipped and nil must be returned.
	// If the received type is a struct or pointer to a struct, the validation should be performed.
	// If the struct is not valid or the validation itself fails, a descriptive error should be returned.
	// Otherwise nil must be returned.
	ValidateStruct(obj interface{}) error
}
var DefaultValidator StructValidator = (*defaultValidator)(validator.New(&validator.Config{TagName: "validate"}))

Directories

Path Synopsis
internal
copy from net/http/pprof
copy from net/http/pprof

Jump to

Keyboard shortcuts

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