ship

package module
v2.5.1 Latest Latest
Warning

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

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

README

ship Build Status GoDoc License

ship is a flexible, powerful, high performance and minimalist Go Web HTTP router framework. It is inspired by echo and httprouter. Thanks for those contributors.

ship has been stable, and the current version is v2 and support Go 1.11+.

Install

go get -u github.com/xgfone/ship/v2

Quick Start

// example.go
package main

import "github.com/xgfone/ship/v2"

func main() {
	router := ship.New()
	router.Route("/ping").GET(func(ctx *ship.Context) error {
		return ctx.JSON(200, map[string]interface{}{"message": "pong"})
	})

	// Start the HTTP server.
	router.Start(":8080").Wait()
	// or
	// http.ListenAndServe(":8080", router)
}
$ go run example.go
$ curl http://127.0.0.1:8080/ping
{"message":"pong"}

API Example

Router
Using Connect, Get, Post, Put, Patch, Delete and Option
func main() {
    router := ship.New()
    router.Route("/path/get").GET(getHandler)
    router.Route("/path/put").PUT(putHandler)
    router.Route("/path/post").POST(postHandler)
    router.Route("/path/patch").PATCH(patchHandler)
    router.Route("/path/delete").DELETE(deleteHandler)
    router.Route("/path/option").OPTIONS(optionHandler)
    router.Route("/path/connect").CONNECT(connectHandler)
    router.Start(":8080").Wait()
}

Notice: you can register the same handler with more than one method by Route(path string).Method(handler Handler, method ...string).

R is the alias of Route, and you can register the routes by R(path string).Method(handler Handler, method ...string).

Cascade the registered routes
func main() {
    router := ship.New()
    router.R("/path/to").GET(getHandler).POST(postHandler).DELETE(deleteHandler)
    router.Start(":8080").Wait()
}

or use the mapping from method to handler:

func main() {
    router := ship.New()
    router.R("/path/to").Map(map[string]ship.Handler{
        "GET": getHandler,
        "POST": postHandler,
        "DELETE": deleteHandler,
    })
    router.Start(":8080").Wait()
}
Naming route and building URL

You can name the route when registering it, then you can build a URL by the name.

func main() {
    router := ship.New()
    router.Route("/path/:id").Name("get_url").GET(func(ctx *ship.Context) error {
        fmt.Println(ctx.URL("get_url", ctx.URLParam("id")))
    })
    router.Start(":8080").Wait()
}
Add the Header filter
func main() {
    router := ship.New()
    handler := func(ctx *ship.Context) error { return nil }

    // The Content-Type header of the request to /path2 must be application/json,
    // Or it will return 404.
    router.R("/path2").HasHeader("Content-Type", "application/json").POST(handler)
    router.Start(":8080").Wait()
}
Map methods into Router
package main

import (
    "net/http"

    "github.com/xgfone/ship/v2"
)

type TestType struct{}

func (t TestType) Create(ctx *ship.Context) error { return nil }
func (t TestType) Delete(ctx *ship.Context) error { return nil }
func (t TestType) Update(ctx *ship.Context) error { return nil }
func (t TestType) Get(ctx *ship.Context) error    { return nil }
func (t TestType) Has(ctx *ship.Context) error    { return nil }
func (t TestType) NotHandler()              {}

func main() {
    router := ship.New()
    router.Route("/v1").MapType(TestType{})
    router.Start(":8080").Wait()
}

router.Route("/v1").MapType(TestType{}) is equal to

tv := TestType{}
router.Route("/v1/testtype/get").Name("testtype_get").GET(tv.Get)
router.Route("/v1/testtype/update").Name("testtype_update").PUT(tv.Update)
router.Route("/v1/testtype/create").Name("testtype_create").POST(tv.Create)
router.Route("/v1/testtype/delete").Name("testtype_delete").DELETE(tv.Delete)

Notice:

  • The name of type and method will be converted to the lower.
  • The mapping format of the route path is %{prefix}/%{lower_type_name}/%{lower_method_name}.
  • The mapping format of the route name is %{lower_type_name}_%{lower_method_name}.
  • The type of the method must be func(*ship.Context) error or it will be ignored.
Using SubRouter
func main() {
    router := ship.New().Use(middleware.Logger(), middleware.Recover())

    // v1 SubRouter, which will inherit the middlewares of the parent router.
    v1 := router.Group("/v1")
    v1.Route("/get/path").GET(getHandler)

    // v2 SubRouter, which won't inherit the middlewares of the parent router.
    v2 := router.Group("/v2").NoMiddlewares().Use(MyAuthMiddleware())
    v2.Route("/post/path").POST(postHandler)

    router.Start(":8080").Wait()
}
Filter the unacceptable route
func filter(ri ship.RouteInfo) bool {
    if ri.Name == "" {
        return true
    } else if !strings.HasPrefix(ri.Path, "/prefix/") {
        return true
    }
    return false
}

func main() {
    // Don't register the router without name.
    app := ship.New()
    app.RouteFilter = filter

    app.Group("/prefix").R("/name").Name("test").GET(handler) // Register the route
    app.Group("/prefix").R("/noname").GET(handler)            // Don't register the route
    app.R("/no_group").GET(handler)                           // Don't register the route
}
Modify the registered route
func modifier(ri ship.RouteInfo) ship.RouteInfo {
    ri.Path = "/prefix" + ri.Path
    return ri
}

func main() {
    app := ship.New()
    app.RouteModifier = modifier

    // Register the path as "/prefix/path".
    app.R("/path").Name("test").GET(handler)
}
Using Middleware
package main

import (
    "net/http"

    "github.com/xgfone/ship/v2"
    "github.com/xgfone/ship/v2/middleware"
)

func main() {
    // We disable the default error log because we have used the Logger middleware.
    app := ship.New().Use(middleware.Logger(), middleware.Recover())
    app.Use(MyAuthMiddleware())
    app.Route("/url/path").GET(handler)
    app.Start(":8080").Wait()
}

You can register a middleware to run before finding the router. You may affect the router finding by registering Before middleware. For example,

package main

import (
    "net/http"

    "github.com/xgfone/ship/v2"
    "github.com/xgfone/ship/v2/middleware"
)

func RemovePathPrefix(prefix string) ship.Middleware {
    if len(prefix) < 2 || prefix[len(prefix)-1] == "/" {
        panic(fmt.Errorf("invalid prefix: '%s'", prefix))
    }

    return func(next ship.Handler) Handler {
        return func(ctx *ship.Context) error {
            req := ctx.Request()
            req.URL.Path = strings.TrimPrefix(req.URL.Path, prefix)
        }
    }
}

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

    // Use and Before have no interference each other.
    router.Use(middleware.Logger())
    router.Pre(RemovePathPrefix("/static"))
    router.Use(middleware.Recover())

    router.Route("/url/path").GET(handler)
    router.Start(":8080").Wait()
}
Add the Virtual Host
package main

import "github.com/xgfone/ship/v2"

func main() {
	router := ship.New()
	router.Route("/router").GET(func(c *ship.Context) error { return c.Text(200, "default") })

	vhost1 := router.Host("host1.example.com") // It is a RouteGroup with the host.
	vhost1.Route("/router").GET(func(c *ship.Context) error { return c.Text(200, "vhost1") })

	vhost2 := router.Host("host2.example.com") // It is a RouteGroup with the host.
	vhost2.Route("/router").GET(func(c *ship.Context) error { return c.Text(200, "vhost2") })

	router.Start(":8080").Wait()
}
$ curl http://127.0.0.1:8080/router
default

$ curl http://127.0.0.1:8080/router -H 'Host: host1.example.com'
vhost1

$ curl http://127.0.0.1:8080/router -H 'Host: host2.example.com'
vhost2
Handle the complex response
package main

import (
	"net/http"

	"github.com/xgfone/ship/v2"
)

func responder(ctx *ship.Context, args ...interface{}) error {
	switch len(args) {
	case 0:
		return ctx.NoContent(http.StatusOK)
	case 1:
		switch v := args[0].(type) {
		case int:
			return ctx.NoContent(v)
		case string:
			return ctx.Text(http.StatusOK, v)
		}
	case 2:
		switch v0 := args[0].(type) {
		case int:
			return ctx.Text(v0, "%v", args[1])
		}
	}
	return ctx.NoContent(http.StatusInternalServerError)
}

func main() {
	app := ship.New()
	app.Responder = responder
	app.Route("/path1").GET(func(c *ship.Context) error { return c.Respond() })
	app.Route("/path2").GET(func(c *ship.Context) error { return c.Respond(200) })
	app.Route("/path3").GET(func(c *ship.Context) error { return c.Respond("Hello, World") })
	app.Route("/path4").GET(func(c *ship.Context) error { return c.Respond(200, "Hello, World") })
	app.Start(":8080").Wait()
}
Bind JSON, XML or Form data form payload

ship supply a default data binding to bind the JSON, XML or Form data from payload.

type Login struct {
    Username string `json:"username" xml:"username"`
    Password string `json:"password" xml:"password"`
}

func main() {
    router := ship.Default()

    router.Route("/login").POST(func(ctx *ship.Context) error {
        var login Login
        if err := ctx.Bind(&login); err != nil {
            return err
        }
        ...
    })

    router.Start(":8080").Wait()
}
Render JSON, XML, HTML or other format data

In the directory /path/to/templates, there is a template file named index.tmpl as follow:

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        This is the body content: </pre>{{ . }}</pre>
    </body>
</html>

So we load it as the template by the stdlib html/template, and render it as the HTML content.

package main

import (
	"fmt"

	"github.com/xgfone/ship/v2"
	"github.com/xgfone/ship/v2/render"
	"github.com/xgfone/ship/v2/render/template"
)

func main() {
	// It will recursively load all the files in the directory as the templates.
	loader := template.NewDirLoader("/path/to/templates")
	tmplRender := template.NewHTMLTemplateRender(loader)

	router := ship.Default()
	router.Renderer.(*render.MuxRenderer).Add(".tmpl", tmplRender)

	// For JSON
	router.Route("/json").GET(func(ctx *ship.Context) error {
		if ctx.QueryParam("pretty") == "1" {
			return ctx.JSONPretty(200, map[string]interface{}{"msg": "json"}, "    ")
			// Or
			// return ctx.RenderOk("jsonpretty", map[string]interface{}{"msg": "json"})
		}
		return ctx.JSON(200, map[string]interface{}{"msg": "json"})
		// Or
		// return ctx.RenderOk("json", map[string]interface{}{"msg": "json"})
	})

	// For XML
	router.Route("/xml").GET(func(ctx *ship.Context) error {
		if ctx.QueryParam("pretty") == "1" {
			return ctx.XMLPretty(200, []string{"msg", "xml"}, "    ")
			// Or
			// return ctx.RenderOk("xmlpretty", []string{"msg", "xml"})
		}
		return ctx.XML(200, []string{"msg", "xml"})
		// Or
		// return ctx.RenderOk("xml", []string{"msg", "xml"})
	})

	// For HTML
	router.Route("/html").GET(func(ctx *ship.Context) error {
		return ctx.RenderOk("index.tmpl", "Hello World")
	})

	// Start the HTTP server.
	router.Start(":8080").Wait()
}

When accessing http://127.0.0.1:8080/html, it returns

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        This is the body content: </pre>Hello World</pre>
    </body>
</html>
Prometheus Metric
package main

import (
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/xgfone/ship/v2"
)

func main() {
	app := ship.New()
	app.R("/metrics").GET(ship.FromHTTPHandler(promhttp.Handler()))
	app.Start(":8080").Wait()
}

You can disable or remove the default collectors like this.

package main

import (
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/xgfone/ship/v2"
)

// DisableBuiltinCollector removes the collectors that the default prometheus
// register registered.
func DisableBuiltinCollector() {
	prometheus.Unregister(prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}))
	prometheus.Unregister(prometheus.NewGoCollector())
}

func main() {
	DisableBuiltinCollector()
	app := ship.New()
	app.R("/metrics").GET(ship.FromHTTPHandler(promhttp.Handler()))
	app.Start(":8080").Wait()
}

The default prometheus HTTP handler, promhttp.Handler(), will collect two metrics: promhttp_metric_handler_requests_in_flight and promhttp_metric_handler_requests_total{code="200/500/503"}. However, you can rewrite it like this.

package main

import (
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/common/expfmt"
	"github.com/xgfone/ship/v2"
)

// DisableBuiltinCollector removes the collectors that the default prometheus
// register registered.
func DisableBuiltinCollector() {
	prometheus.Unregister(prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}))
	prometheus.Unregister(prometheus.NewGoCollector())
}

// Prometheus returns a prometheus handler.
//
// if missing gatherer, it is prometheus.DefaultGatherer by default.
func Prometheus(gatherer ...prometheus.Gatherer) ship.Handler {
	gather := prometheus.DefaultGatherer
	if len(gatherer) > 0 && gatherer[0] != nil {
		gather = gatherer[0]
	}

	return func(ctx *ship.Context) error {
		mfs, err := gather.Gather()
		if err != nil {
			return err
		}

		ct := expfmt.Negotiate(ctx.Request().Header)
		ctx.SetContentType(string(ct))
		enc := expfmt.NewEncoder(ctx, ct)

		for _, mf := range mfs {
			if err = enc.Encode(mf); err != nil {
				ctx.Logger().Errorf("failed to encode prometheus metric: %s", err)
			}
		}

		return nil
	}
}

func main() {
	DisableBuiltinCollector()
	ship.New().R("/metrics").GET(Prometheus()).Ship().Start(":8080").Wait()
}

Route Management

ship supply a default implementation based on Radix tree to manage the route with Zero Garbage (See Benchmark), which refers to echo, that's, NewRouter().

You can appoint your own implementation by implementing the interface Router.

type Router interface {
	// Generate a URL by the url name and parameters.
	URL(name string, params ...interface{}) string

	// Add a route with name, path, method and handler, and return the number
	// of the parameters if there are the parameters in the route. Or return 0.
	//
	// If there is any error, it should panic.
	//
	// Notice: for keeping consistent, the parameter should start with ":"
	// or "*". ":" stands for a single parameter, and "*" stands for
	// a wildcard parameter.
	Add(name, method, path string, handler interface{}) (paramNum int)

	// Find a route handler by the method and path of the request.
	//
	// Return defaultHandler instead if the route does not exist.
	//
	// If the route has parameters, the name and value of the parameters
	// should be stored `pnames` and `pvalues` respectively, which has
	// the enough capacity to store the paramether names and values.
	Find(method, path string, pnames, pvalues []string,
		defaultHandler interface{}) (handler interface{})
}
func main() {
    NewMyRouter := func() ship.Router { return ... }
    router := ship.New().SetNewRouter(NewMyRouter)
    // ...
}

Benchmark

Test 1
Dell Vostro 3470
Intel Core i5-7400 3.0GHz
8GB DDR4 2666MHz
Windows 10
Go 1.13.4
Function ops ns/op bytes/opt allocs/op
BenchmarkGinStatic-4 23368 49788 8278 157
BenchmarkGinGitHubAPI-4 15684 75104 10849 203
BenchmarkGinGplusAPI-4 276224 4184 686 13
BenchmarkGinParseAPI-4 157810 7537 1357 26
BenchmarkEchoStatic-4 29432 39989 2432 157
BenchmarkEchoGitHubAPI-4 20527 56857 2468 203
BenchmarkEchoGplusAPI-4 387421 3179 193 13
BenchmarkEchoParseAPI-4 220273 5575 365 26
BenchmarkShipEchoStatic-4 34054 35548 1016 0
BenchmarkShipEchoGitHubAPI-4 21842 54962 1585 0
BenchmarkShipEchoGplusAPI-4 402898 2996 85 0
BenchmarkShipEchoParseAPI-4 223581 5478 154 0
Test 2
MacBook Pro(Retina, 13-inch, Mid 2014)
Intel Core i5 2.6GHz
8GB DDR3 1600MHz
macOS Mojave
Go 1.13.4
Function ops ns/op bytes/opt allocs/op
BenchmarkGinStatic-4 18085 62380 8494 157
BenchmarkGinGitHubAPI-4 12646 93052 11115 203
BenchmarkGinGplusAPI-4 224404 5222 701 13
BenchmarkGinParseAPI-4 124138 9442 1387 26
BenchmarkEchoStatic-4 22624 47401 2021 157
BenchmarkEchoGitHubAPI-4 16822 69059 2654 203
BenchmarkEchoGplusAPI-4 326142 3759 157 13
BenchmarkEchoParseAPI-4 178182 6713 402 26
BenchmarkShipEchoStatic-4 27048 43713 640 0
BenchmarkShipEchoGitHubAPI-4 17545 66953 987 0
BenchmarkShipEchoGplusAPI-4 318595 3698 54 0
BenchmarkShipEchoParseAPI-4 175984 6807 196 0

Documentation

Overview

Package ship has implemented a flexible, powerful, high performance and minimalist Go Web HTTP router framework, which is inspired by echo and httprouter.

Index

Constants

View Source
const (
	CharsetUTF8 = "charset=UTF-8"
	PROPFIND    = "PROPFIND"
)

Predefine some variables

View Source
const (
	MIMEApplicationJSON                  = "application/json"
	MIMEApplicationJSONCharsetUTF8       = MIMEApplicationJSON + "; " + CharsetUTF8
	MIMEApplicationJavaScript            = "application/javascript"
	MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + CharsetUTF8
	MIMEApplicationXML                   = "application/xml"
	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 (
	HeaderAccept              = "Accept"
	HeaderAcceptedLanguage    = "Accept-Language"
	HeaderAcceptEncoding      = "Accept-Encoding"
	HeaderAllow               = "Allow"
	HeaderAuthorization       = "Authorization"
	HeaderConnection          = "Connection"
	HeaderContentDisposition  = "Content-Disposition"
	HeaderContentEncoding     = "Content-Encoding"
	HeaderContentLength       = "Content-Length"
	HeaderContentType         = "Content-Type"
	HeaderCookie              = "Cookie"
	HeaderSetCookie           = "Set-Cookie"
	HeaderIfModifiedSince     = "If-Modified-Since"
	HeaderLastModified        = "Last-Modified"
	HeaderEtag                = "Etag"
	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"
	HeaderReferer             = "Referer"
	HeaderUserAgent           = "User-Agent"

	// 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"
	HeaderXCSRFToken              = "X-CSRF-Token"
)

Headers

Variables

View Source
var (
	MIMEApplicationJSONs                  = []string{MIMEApplicationJSON}
	MIMEApplicationJSONCharsetUTF8s       = []string{MIMEApplicationJSONCharsetUTF8}
	MIMEApplicationJavaScripts            = []string{MIMEApplicationJavaScript}
	MIMEApplicationJavaScriptCharsetUTF8s = []string{MIMEApplicationJavaScriptCharsetUTF8}
	MIMEApplicationXMLs                   = []string{MIMEApplicationXML}
	MIMEApplicationXMLCharsetUTF8s        = []string{MIMEApplicationXMLCharsetUTF8}
	MIMETextXMLs                          = []string{MIMETextXML}
	MIMETextXMLCharsetUTF8s               = []string{MIMETextXMLCharsetUTF8}
	MIMEApplicationForms                  = []string{MIMEApplicationForm}
	MIMEApplicationProtobufs              = []string{MIMEApplicationProtobuf}
	MIMEApplicationMsgpacks               = []string{MIMEApplicationMsgpack}
	MIMETextHTMLs                         = []string{MIMETextHTML}
	MIMETextHTMLCharsetUTF8s              = []string{MIMETextHTMLCharsetUTF8}
	MIMETextPlains                        = []string{MIMETextPlain}
	MIMETextPlainCharsetUTF8s             = []string{MIMETextPlainCharsetUTF8}
	MIMEMultipartForms                    = []string{MIMEMultipartForm}
	MIMEOctetStreams                      = []string{MIMEOctetStream}
)

MIME slice types

View Source
var (
	// Some non-HTTP errors
	ErrMissingContentType    = herror.ErrMissingContentType
	ErrRendererNotRegistered = herror.ErrRendererNotRegistered
	ErrInvalidRedirectCode   = herror.ErrInvalidRedirectCode
	ErrInvalidSession        = herror.ErrInvalidSession
	ErrSessionNotExist       = herror.ErrSessionNotExist
	ErrNoSessionSupport      = herror.ErrNoSessionSupport
	ErrNoResponder           = herror.ErrNoResponder

	// Some HTTP error.
	ErrBadRequest                    = herror.ErrBadRequest
	ErrUnauthorized                  = herror.ErrUnauthorized
	ErrForbidden                     = herror.ErrForbidden
	ErrNotFound                      = herror.ErrNotFound
	ErrMethodNotAllowed              = herror.ErrMethodNotAllowed
	ErrStatusNotAcceptable           = herror.ErrStatusNotAcceptable
	ErrRequestTimeout                = herror.ErrRequestTimeout
	ErrStatusConflict                = herror.ErrStatusConflict
	ErrStatusGone                    = herror.ErrStatusGone
	ErrStatusRequestEntityTooLarge   = herror.ErrStatusRequestEntityTooLarge
	ErrUnsupportedMediaType          = herror.ErrUnsupportedMediaType
	ErrTooManyRequests               = herror.ErrTooManyRequests
	ErrInternalServerError           = herror.ErrInternalServerError
	ErrStatusNotImplemented          = herror.ErrStatusNotImplemented
	ErrBadGateway                    = herror.ErrBadGateway
	ErrServiceUnavailable            = herror.ErrServiceUnavailable
	ErrStatusGatewayTimeout          = herror.ErrStatusGatewayTimeout
	ErrStatusHTTPVersionNotSupported = herror.ErrStatusHTTPVersionNotSupported

	// ErrSkip is not an error, which is used to suggest that the middeware
	// should skip and return it back to the outer middleware to handle.
	ErrSkip = herror.ErrSkip
)

Re-export some errors.

AllMethods represents all HTTP methods.

View Source
var DefaultMethodMapping = map[string]string{
	"Create": "POST",
	"Delete": "DELETE",
	"Update": "PUT",
	"Get":    "GET",
}

DefaultMethodMapping is the default method mapping of the route.

View Source
var DefaultShip = Default()

DefaultShip is the default global ship.

DefaultSignals is a set of default signals.

View Source
var MaxMemoryLimit int64 = 32 << 20 // 32MB

MaxMemoryLimit is the maximum memory.

View Source
var NewHTTPError = herror.NewHTTPError

NewHTTPError is the alias of herror.NewHTTPError.

Functions

func AddContentTypeToSlice

func AddContentTypeToSlice(contentType string, contentTypeSlice []string)

AddContentTypeToSlice add a rule to convert contentType to contentTypeSlice. So you can call SetContentType to set the Content-Type to contentTypeSlice by contentType to avoid to allocate the memory.

func PutResponseIntoPool

func PutResponseIntoPool(r *Response)

PutResponseIntoPool puts a Response into the pool.

func ReadNWriter

func ReadNWriter(w io.Writer, r io.Reader, n int64) (err error)

ReadNWriter reads n bytes to the writer w from the reader r.

It will return io.EOF if the length of the data from r is less than n. But the data has been read into w.

func SetContentType

func SetContentType(res http.ResponseWriter, ct string)

SetContentType is equal to SetHeaderContentType(res.Header(), ct).

func SetHeaderContentType

func SetHeaderContentType(header http.Header, ct string)

SetHeaderContentType sets the Content-Type header to ct.

func ToHTTPHandler

func ToHTTPHandler(s *Ship, h Handler) http.Handler

ToHTTPHandler converts the Handler to http.Handler

Types

type BufferAllocator

type BufferAllocator interface {
	AcquireBuffer() *bytes.Buffer
	ReleaseBuffer(*bytes.Buffer)
}

BufferAllocator is used to acquire and release a buffer.

type Context

type Context struct {
	// Data is used to store many key-value pairs about the context.
	//
	// Data maybe asks the system to allocate many memories.
	// If the interim context value is too few and you don't want the system
	// to allocate many memories, the three context variables is for you
	// and you can consider them as the context register to use.
	//
	// Notice: when the new request is coming, they will be reset to nil.
	Key1 interface{}
	Key2 interface{}
	Key3 interface{}
	Data map[string]interface{}
	// contains filtered or unexported fields
}

Context represetns a request and response context.

func NewContext

func NewContext(urlParamMaxNum, dataSize int) *Context

NewContext returns a new Context.

func (*Context) Accept

func (c *Context) Accept() []string

Accept returns the content of the header Accept.

If there is no the header Accept , it return nil.

Notice:

  1. It will sort the content by the q-factor weighting.
  2. If the value is "<MIME_type>/*", it will be amended as "<MIME_type>/". So you can use it to match the prefix.
  3. If the value is "*/*", it will be amended as "".

func (*Context) AcquireBuffer

func (c *Context) AcquireBuffer() *bytes.Buffer

AcquireBuffer acquires a buffer.

Notice: you should call ReleaseBuffer() to release it.

func (*Context) AddHeader

func (c *Context) AddHeader(name, value string)

AddHeader appends the value for the response header name.

func (*Context) Attachment

func (c *Context) Attachment(file string, name string) error

Attachment sends a response as attachment, prompting client to save the file.

If the file does not exist, it returns ErrNotFound.

func (*Context) BasicAuth

func (c *Context) BasicAuth() (username, password string, ok bool)

BasicAuth returns the username and password from the request.

func (*Context) Bind

func (c *Context) Bind(v interface{}) error

Bind binds the request information into the provided value v.

The default binder does it based on Content-Type header.

func (*Context) BindQuery

func (c *Context) BindQuery(v interface{}) error

BindQuery binds the request URL query into the provided value v.

func (*Context) Blob

func (c *Context) Blob(code int, contentType string, b []byte) (err error)

Blob sends a blob response with status code and content type.

func (*Context) BlobText

func (c *Context) BlobText(code int, contentType string, format string,
	args ...interface{}) (err error)

BlobText sends a string blob response with status code and content type.

func (*Context) Body

func (c *Context) Body() io.ReadCloser

Body returns the reader of the request body.

func (*Context) Charset

func (c *Context) Charset() string

Charset returns the charset of the request content.

Return "" if there is no charset.

func (*Context) ClearData

func (c *Context) ClearData()

ClearData clears the data.

func (*Context) ContentLength

func (c *Context) ContentLength() int64

ContentLength return the length of the request body.

func (*Context) ContentType

func (c *Context) ContentType() (ct string)

ContentType returns the Content-Type of the request without the charset.

func (*Context) Cookie

func (c *Context) Cookie(name string) *http.Cookie

Cookie returns the named cookie provided in the request.

Return nil if no the cookie named name.

func (*Context) Cookies

func (c *Context) Cookies() []*http.Cookie

Cookies returns the HTTP cookies sent with the request.

func (*Context) DelHeader

func (c *Context) DelHeader(name string)

DelHeader deletes the header named name from the response.

func (*Context) DelSession

func (c *Context) DelSession(id string) (err error)

DelSession deletes the session from the backend store.

func (*Context) Error

func (c *Context) Error(code int, err error) HTTPError

Error sends an error response with status code.

func (*Context) Execute

func (c *Context) Execute(notFound Handler) error

Execute finds the route and calls the handler.

SetRouter must be called before calling Execute, which be done by the framework.

func (*Context) File

func (c *Context) File(file string) (err error)

File sends a response with the content of the file.

If the file does not exist, it returns ErrNotFound.

If not set the Content-Type, it will deduce it from the extension of the file name.

func (*Context) FormFile

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

FormFile returns the multipart form file for the provided name.

func (*Context) FormParams

func (c *Context) FormParams() (url.Values, error)

FormParams returns the form parameters as `url.Values`.

func (*Context) FormValue

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

FormValue returns the form field value for the provided name.

func (*Context) GetBody

func (c *Context) GetBody() (string, error)

GetBody reads all the contents from the body and returns it as string.

func (*Context) GetBodyReader

func (c *Context) GetBodyReader() (buf *bytes.Buffer, err error)

GetBodyReader reads all the contents from the body to buffer and returns it.

Notice: You should call ReleaseBuffer(buf) to release the buffer at last.

func (*Context) GetHeader

func (c *Context) GetHeader(name string) string

GetHeader returns the first value of the request header named name.

Return "" if the header does not exist.

func (*Context) GetSession

func (c *Context) GetSession(id string) (v interface{}, err error)

GetSession returns the session content by id from the backend store.

If the session id does not exist, it returns ErrSessionNotExist.

func (*Context) HTML

func (c *Context) HTML(code int, html string) error

HTML sends an HTTP response with status code.

func (*Context) HTMLBlob

func (c *Context) HTMLBlob(code int, b []byte) error

HTMLBlob sends an HTTP blob response with status code.

func (*Context) Header

func (c *Context) Header() http.Header

Header is equal to RespHeader().

func (*Context) Host

func (c *Context) Host() string

Host returns the host of the request.

func (*Context) Hostname

func (c *Context) Hostname() string

Hostname returns the hostname of the request.

func (*Context) Inline

func (c *Context) Inline(file string, name string) error

Inline sends a response as inline, opening the file in the browser.

If the file does not exist, it returns ErrNotFound.

func (*Context) IsAjax

func (c *Context) IsAjax() bool

IsAjax reports whether the request is ajax or not.

func (*Context) IsResponded

func (c *Context) IsResponded() bool

IsResponded reports whether the response is sent.

func (*Context) IsTLS

func (c *Context) IsTLS() bool

IsTLS reports whether HTTP connection is TLS or not.

func (*Context) IsWebSocket

func (c *Context) IsWebSocket() bool

IsWebSocket reports whether HTTP connection is WebSocket or not.

func (*Context) JSON

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

JSON sends a JSON response with status code.

func (*Context) JSONBlob

func (c *Context) JSONBlob(code int, b []byte) error

JSONBlob sends a JSON blob response with status code.

func (*Context) JSONP

func (c *Context) JSONP(code int, callback string, i interface{}) error

JSONP sends a JSONP response with status code. It uses `callback` to construct the JSONP payload.

func (*Context) JSONPBlob

func (c *Context) JSONPBlob(code int, callback string, b []byte) (err error)

JSONPBlob sends a JSONP blob response with status code. It uses `callback` to construct the JSONP payload.

func (*Context) JSONPretty

func (c *Context) JSONPretty(code int, v interface{}, indent string) error

JSONPretty sends a pretty-print JSON with status code.

func (*Context) Logger

func (c *Context) Logger() Logger

Logger returns the logger.

func (*Context) Method

func (c *Context) Method() string

Method returns the method of the request.

func (*Context) MultipartForm

func (c *Context) MultipartForm() (*multipart.Form, error)

MultipartForm returns the multipart form.

func (*Context) MultipartReader

func (c *Context) MultipartReader() (*multipart.Reader, error)

MultipartReader returns the multipart reader from the request.

func (*Context) NoContent

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

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

func (*Context) NotFoundHandler

func (c *Context) NotFoundHandler() Handler

NotFoundHandler returns the NotFound Handler, but returns nil instead if not set.

func (*Context) Path

func (c *Context) Path() string

Path returns the path of the request.

func (*Context) QueryParam

func (c *Context) QueryParam(name string) string

QueryParam returns the query param for the provided name.

func (*Context) QueryParams

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

QueryParams returns the query parameters as `url.Values`.

func (*Context) QueryRawString

func (c *Context) QueryRawString() string

QueryRawString returns the URL query string.

func (*Context) RealIP

func (c *Context) RealIP() string

RealIP returns the client's network address based on `X-Forwarded-For` or `X-Real-IP` request header.

func (*Context) Redirect

func (c *Context) Redirect(code int, toURL string) error

Redirect redirects the request to a provided URL with status code.

func (*Context) Referer

func (c *Context) Referer() string

Referer returns the Referer header of the request.

func (*Context) ReleaseBuffer

func (c *Context) ReleaseBuffer(buf *bytes.Buffer)

ReleaseBuffer releases a buffer into the pool.

func (*Context) RemoteAddr

func (c *Context) RemoteAddr() string

RemoteAddr returns the remote address of the http connection.

func (*Context) Render

func (c *Context) Render(name string, code int, data interface{}) error

Render renders a template named name with data and sends a text/html response with status code.

func (*Context) RenderOk added in v2.5.0

func (c *Context) RenderOk(name string, data interface{}) error

RenderOk is short for c.Render(name, http.StatusOK, data).

func (*Context) ReqHeader

func (c *Context) ReqHeader() http.Header

ReqHeader returns the header of the request.

func (*Context) Request

func (c *Context) Request() *http.Request

Request returns the inner Request.

func (*Context) RequestURI

func (c *Context) RequestURI() string

RequestURI returns the URI of the request.

func (*Context) Reset

func (c *Context) Reset()

Reset resets the context to the initalizing state.

func (*Context) RespHeader

func (c *Context) RespHeader() http.Header

RespHeader returns the header of the response.

func (*Context) Respond

func (c *Context) Respond(args ...interface{}) error

Respond calls the context handler set by SetHandler.

Return ErrNoResponder if the context handler or the global handler is not set.

func (*Context) Response

func (c *Context) Response() *Response

Response returns the inner Response.

func (*Context) ResponseWriter

func (c *Context) ResponseWriter() http.ResponseWriter

ResponseWriter returns the underlying http.ResponseWriter.

func (*Context) Router

func (c *Context) Router() router.Router

Router returns the router.

func (*Context) Scheme

func (c *Context) Scheme() (scheme string)

Scheme returns the HTTP protocol scheme, `http` or `https`.

func (*Context) SetBinder

func (c *Context) SetBinder(b binder.Binder)

SetBinder sets the binder to b to bind the request information to an object.

func (*Context) SetBufferAllocator

func (c *Context) SetBufferAllocator(alloc BufferAllocator)

SetBufferAllocator sets the buffer allocator to alloc.

func (*Context) SetConnectionClose

func (c *Context) SetConnectionClose()

SetConnectionClose tell the server to close the connection.

func (*Context) SetContentType

func (c *Context) SetContentType(ct string)

SetContentType sets the Content-Type header of the response body to ct, but does nothing if contentType is "".

func (*Context) SetCookie

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

SetCookie adds a `Set-Cookie` header in HTTP response.

func (*Context) SetGetURL

func (c *Context) SetGetURL(getURL func(name string, params ...interface{}) string)

SetGetURL sets the url getter to getURL.

func (*Context) SetHeader

func (c *Context) SetHeader(name, value string)

SetHeader sets the response header name to value.

func (*Context) SetLogger

func (c *Context) SetLogger(logger Logger)

SetLogger sets the logger to logger.

func (*Context) SetNotFoundHandler

func (c *Context) SetNotFoundHandler(notFound Handler)

SetNotFoundHandler sets the NotFound handler.

func (*Context) SetQueryBinder

func (c *Context) SetQueryBinder(f func(interface{}, url.Values) error)

SetQueryBinder sets the query binder to f to bind the url query to an object.

func (*Context) SetRenderer

func (c *Context) SetRenderer(r render.Renderer)

SetRenderer sets the renderer to r to render the response to the peer.

func (*Context) SetReqRes

func (c *Context) SetReqRes(r *http.Request, w http.ResponseWriter)

SetReqRes is the same as Reset, but only reset the request and response, not all things.

func (*Context) SetRequest

func (c *Context) SetRequest(req *http.Request)

SetRequest resets the request to req.

func (*Context) SetResponder

func (c *Context) SetResponder(h func(*Context, ...interface{}) error)

SetResponder sets the responder to handle the complicated response.

For example,

responder := func(ctx *Context, args ...interface{}) error {
    switch len(args) {
    case 0:
        return ctx.NoContent(http.StatusOK)
    case 1:
        switch v := args[0].(type) {
        case int:
            return ctx.NoContent(v)
        case string:
            return ctx.Text(http.StatusOK, v)
        }
    case 2:
        switch v0 := args[0].(type) {
        case int:
            return ctx.Text(v0, "%v", args[1])
        }
    }
    return ctx.NoContent(http.StatusInternalServerError)
}

router := New()
router.Responder =responder
router.Route("/path1").GET(func(c *Context) error { return c.Handle() })
router.Route("/path2").GET(func(c *Context) error { return c.Handle(200) })
router.Route("/path3").GET(func(c *Context) error { return c.Handle("Hello, World") })
router.Route("/path4").GET(func(c *Context) error { return c.Handle(200, "Hello, World") })

func (*Context) SetResponse

func (c *Context) SetResponse(res http.ResponseWriter)

SetResponse resets the response to resp, which will ignore nil.

func (*Context) SetRouter

func (c *Context) SetRouter(r router.Router)

SetRouter sets the router to r.

func (*Context) SetSession

func (c *Context) SetSession(id string, value interface{}) (err error)

SetSession sets the session to the backend store.

func (*Context) SetSessionManagement

func (c *Context) SetSessionManagement(s session.Session)

SetSessionManagement sets the session management to s.

func (*Context) StatusCode

func (c *Context) StatusCode() int

StatusCode returns the status code of the response.

func (*Context) Stream

func (c *Context) Stream(code int, contentType string, r io.Reader) (err error)

Stream sends a streaming response with status code and content type.

func (*Context) Text

func (c *Context) Text(code int, format string, args ...interface{}) error

Text sends a string response with status code.

func (*Context) URL

func (c *Context) URL(name string, params ...interface{}) string

URL generates an URL by route name and provided parameters.

Return "" if there is no the route named name.

func (*Context) URLParam

func (c *Context) URLParam(name string) string

URLParam returns the parameter value in the url path by name.

func (*Context) URLParamNames

func (c *Context) URLParamNames() []string

URLParamNames returns the names of all the URL parameters.

func (*Context) URLParamValues

func (c *Context) URLParamValues() []string

URLParamValues returns the values of all the URL parameters.

func (*Context) URLParams

func (c *Context) URLParams() map[string]string

URLParams returns all the parameters as the key-value map in the url path.

func (*Context) UserAgent

func (c *Context) UserAgent() string

UserAgent returns the User-Agent header of the request.

func (*Context) Write

func (c *Context) Write(b []byte) (int, error)

Write writes the content to the peer.

it will write the header firstly with 200 if the header is not sent.

func (*Context) WriteHeader

func (c *Context) WriteHeader(statusCode int)

WriteHeader sends an HTTP response header with the provided status code.

func (*Context) XML

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

XML sends an XML response with status code.

func (*Context) XMLBlob

func (c *Context) XMLBlob(code int, b []byte) (err error)

XMLBlob sends an XML blob response with status code.

func (*Context) XMLPretty

func (c *Context) XMLPretty(code int, v interface{}, indent string) error

XMLPretty sends a pretty-print XML with status code.

type HTTPError

type HTTPError = herror.HTTPError

HTTPError is the alias of herror.HTTPError.

type Handler

type Handler func(*Context) error

Handler is a handler of the HTTP request.

func FromHTTPHandler

func FromHTTPHandler(h http.Handler) Handler

FromHTTPHandler converts http.Handler to Handler.

func FromHTTPHandlerFunc

func FromHTTPHandlerFunc(h http.HandlerFunc) Handler

FromHTTPHandlerFunc converts http.HandlerFunc to Handler.

func MethodNotAllowedHandler

func MethodNotAllowedHandler() Handler

MethodNotAllowedHandler returns a MethodNotAllowed handler.

func NotFoundHandler

func NotFoundHandler() Handler

NotFoundHandler returns a NotFound handler.

func NothingHandler

func NothingHandler() Handler

NothingHandler returns a Handler doing nothing.

func OkHandler

func OkHandler() Handler

OkHandler returns a Handler only sending the response "200 OK"

type Logger

type Logger interface {
	Tracef(format string, args ...interface{})
	Debugf(foramt string, args ...interface{})
	Infof(foramt string, args ...interface{})
	Warnf(foramt string, args ...interface{})
	Errorf(foramt string, args ...interface{})
}

Logger is logger interface.

Notice: The implementation maybe also has the method { Writer() io.Writer } to get the underlynig writer.

func NewLoggerFromStdlog

func NewLoggerFromStdlog(logger *log.Logger) Logger

NewLoggerFromStdlog converts stdlib log to Logger.

Notice: the returned logger has also implemented the interface { Writer() io.Writer }.

func NewLoggerFromWriter

func NewLoggerFromWriter(w io.Writer, prefix string, flags ...int) Logger

NewLoggerFromWriter returns a new logger by creating a new stdlib log.

Notice: the returned logger has also implemented the interface { Writer() io.Writer }.

type Middleware

type Middleware func(Handler) Handler

Middleware represents a middleware.

type OnceRunner

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

OnceRunner is used to run the task only once, which is different from sync.Once, the second calling does not wait until the first calling finishes.

func NewOnceRunner

func NewOnceRunner(task func()) *OnceRunner

NewOnceRunner returns a new OnceRunner.

func (*OnceRunner) Run

func (r *OnceRunner) Run()

Run runs the task.

type Response

type Response struct {
	http.ResponseWriter

	Size   int64
	Wrote  bool
	Status int
}

Response implements http.ResponseWriter.

func GetResponseFromPool

func GetResponseFromPool(w http.ResponseWriter) *Response

GetResponseFromPool returns a Response from the pool.

func NewResponse

func NewResponse(w http.ResponseWriter) *Response

NewResponse returns a new instance of Response.

func (*Response) Flush added in v2.1.0

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.ir/pkg/net/http/#Flusher)

func (*Response) Hijack added in v2.1.0

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

Hijack implements the http.Hijacker interface to allow an HTTP handler to take over the connection.

See http.Hijacker(https://golang.ir/pkg/net/http/#Hijacker)

func (*Response) Push added in v2.1.0

func (r *Response) Push(target string, opts *http.PushOptions) error

Push implements the http.Pusher interface to support HTTP/2 server push.

See http.Pusher(https://golang.ir/pkg/net/http/#Pusher)

func (*Response) Reset

func (r *Response) Reset(w http.ResponseWriter)

Reset resets the response to the initialized and returns itself.

func (*Response) SetWriter

func (r *Response) SetWriter(w http.ResponseWriter)

SetWriter resets the writer to w and return itself.

func (*Response) Write

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

Write implements http.ResponseWriter#Writer().

func (*Response) WriteHeader

func (r *Response) WriteHeader(code int)

WriteHeader implements http.ResponseWriter#WriteHeader().

func (*Response) WriteString

func (r *Response) WriteString(s string) (n int, err error)

WriteString implements io.StringWriter.

type Route

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

Route represents a route information.

func (*Route) Any

func (r *Route) Any(handler Handler) *Route

Any registers all the supported methods , which is short for r.Method(handler, AllMethods...)

func (*Route) CONNECT

func (r *Route) CONNECT(handler Handler) *Route

CONNECT is the short for r.Method(handler, "CONNECT").

func (*Route) DELETE

func (r *Route) DELETE(handler Handler) *Route

DELETE is the short for r.Method(handler, "DELETE").

func (*Route) GET

func (r *Route) GET(handler Handler) *Route

GET is the short for r.Method(handler, "GET").

func (*Route) Group

func (r *Route) Group() *RouteGroup

Group returns the group that the current route belongs to.

Notice: it will return nil if the route is from ship.Route.

func (*Route) HEAD

func (r *Route) HEAD(handler Handler) *Route

HEAD is the short for r.Method(handler, "HEAD").

func (*Route) HasHeader

func (r *Route) HasHeader(headerK string, headerV ...string) *Route

HasHeader checks whether the request contains the request header. If no, the request will be rejected.

If the header value is given, it will be tested to match.

Example

s := ship.New()
// The request must contains the header "Content-Type: application/json".
s.R("/path/to").HasHeader("Content-Type", "application/json").POST(handler)

func (*Route) Host

func (r *Route) Host(host string) *Route

Host sets the host of the route to host.

func (*Route) Map

func (r *Route) Map(method2handlers map[string]Handler) *Route

Map registers a group of methods with handlers, which is equal to

for method, handler := range method2handlers {
    r.Method(handler, method)
}

func (*Route) MapType

func (r *Route) MapType(tv interface{}) *Route

MapType registers the methods of a type as the routes.

By default, mapping is Ship.Config.DefaultMethodMapping if not given.

Example

type TestType struct{}
func (t TestType) Create(ctx *ship.Context) error { return nil }
func (t TestType) Delete(ctx *ship.Context) error { return nil }
func (t TestType) Update(ctx *ship.Context) error { return nil }
func (t TestType) Get(ctx *ship.Context) error    { return nil }
func (t TestType) Has(ctx *ship.Context) error    { return nil }
func (t TestType) NotHandler()                   {}

router := ship.New()
router.Route("/path/to").MapType(TestType{})

It's equal to the operation as follow:

router.Route("/v1/testtype/get").Name("testtype_get").GET(ts.Get)
router.Route("/v1/testtype/update").Name("testtype_update").PUT(ts.Update)
router.Route("/v1/testtype/create").Name("testtype_create").POST(ts.Create)
router.Route("/v1/testtype/delete").Name("testtype_delete").DELETE(ts.Delete)

If you don't like the default mapping policy, you can give the customized mapping by the last argument, the key of which is the name of the method of the type, and the value of that is the request method, such as GET, POST, etc. Notice that the method type must be compatible with

func (*Context) error

Notice: the name of type and method will be converted to the lower.

func (*Route) Method

func (r *Route) Method(handler Handler, methods ...string) *Route

Method sets the methods and registers the route.

If methods is nil, it will register all the supported methods for the route.

Notice: The method must be called at last.

func (*Route) Name

func (r *Route) Name(name string) *Route

Name sets the route name.

func (*Route) New

func (r *Route) New() *Route

New clones a new Route based on the current route.

func (*Route) NoMiddlewares

func (r *Route) NoMiddlewares() *Route

NoMiddlewares clears all the middlewares and returns itself.

func (*Route) OPTIONS

func (r *Route) OPTIONS(handler Handler) *Route

OPTIONS is the short for r.Method(handler, "OPTIONS").

func (*Route) PATCH

func (r *Route) PATCH(handler Handler) *Route

PATCH is the short for r.Method(handler, "PATCH").

func (*Route) POST

func (r *Route) POST(handler Handler) *Route

POST is the short for r.Method(handler, "POST").

func (*Route) PUT

func (r *Route) PUT(handler Handler) *Route

PUT is the short for r.Method(handler, "PUT").

func (*Route) Redirect

func (r *Route) Redirect(code int, toURL string, method ...string) *Route

Redirect is used to redirect the path to toURL.

method is GET by default.

func (*Route) Ship

func (r *Route) Ship() *Ship

Ship returns the ship that the current route is associated with.

func (*Route) Static

func (r *Route) Static(dirpath string) *Route

Static is the same as StaticFS, but listing the files for a directory.

func (*Route) StaticFS

func (r *Route) StaticFS(fs http.FileSystem) *Route

StaticFS registers a route to serve a static filesystem.

func (*Route) StaticFile

func (r *Route) StaticFile(filePath string) *Route

StaticFile registers a route for a static file, which supports the HEAD method to get the its length and the GET method to download it.

func (*Route) TRACE

func (r *Route) TRACE(handler Handler) *Route

TRACE is the short for r.Method(handler, "TRACE").

func (*Route) Use

func (r *Route) Use(middlewares ...Middleware) *Route

Use adds some middlwares for the route.

type RouteFilter

type RouteFilter func(RouteInfo) bool

RouteFilter is used to filter the registering route if it returns true.

type RouteGroup

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

RouteGroup is a route group, that's, it manages a set of routes.

func (*RouteGroup) AddRoutes added in v2.4.0

func (g *RouteGroup) AddRoutes(ris ...RouteInfo)

AddRoutes adds the routes by RouteInfo.

func (*RouteGroup) Group

func (g *RouteGroup) Group(prefix string, middlewares ...Middleware) *RouteGroup

Group returns a new sub-group.

func (*RouteGroup) Host

func (g *RouteGroup) Host(host string) *RouteGroup

Host sets the host of the route group to host.

func (*RouteGroup) NoMiddlewares

func (g *RouteGroup) NoMiddlewares() *RouteGroup

NoMiddlewares clears all the middlewares and returns itself.

func (*RouteGroup) R

func (g *RouteGroup) R(path string) *Route

R is short for Group#Route(path).

func (*RouteGroup) Route

func (g *RouteGroup) Route(path string) *Route

Route returns a new route, then you can customize and register it.

You must call Route.Method() or its short method.

func (*RouteGroup) Ship

func (g *RouteGroup) Ship() *Ship

Ship returns the ship that the current group belongs to.

func (*RouteGroup) Use

func (g *RouteGroup) Use(middlewares ...Middleware) *RouteGroup

Use adds some middlwares for the group and returns the origin group to write the chained router.

type RouteInfo

type RouteInfo struct {
	Name    string        `json:"name" xml:"name"`
	Host    string        `json:"host" xml:"host"`
	Path    string        `json:"path" xml:"path"`
	Method  string        `json:"method" xml:"method"`
	Handler Handler       `json:"-" xml:"-"`
	Router  router.Router `json:"-" xml:"-"`
}

RouteInfo is used to represent the information of the registered route.

func HTTPPprofToRouteInfo added in v2.3.0

func HTTPPprofToRouteInfo() []RouteInfo

HTTPPprofToRouteInfo converts http pprof handler to RouteInfo, so that you can register them and get runtime profiling data by HTTP server.

type RouteModifier

type RouteModifier func(RouteInfo) RouteInfo

RouteModifier is used to modify the registering route.

type Runner

type Runner struct {
	Name      string
	Logger    Logger
	Server    *http.Server
	Handler   http.Handler
	Signals   []os.Signal
	ConnState func(net.Conn, http.ConnState)
	// contains filtered or unexported fields
}

Runner is a HTTP Server runner.

func NewRunner

func NewRunner(name string, handler http.Handler) *Runner

NewRunner returns a new Runner.

func (r *Runner) Link(other *Runner) *Runner

Link registers the shutdown function between itself and other, then returns itself.

func (*Runner) RegisterOnShutdown

func (r *Runner) RegisterOnShutdown(functions ...func()) *Runner

RegisterOnShutdown registers some functions to run when the http server is shut down.

func (*Runner) Shutdown

func (r *Runner) Shutdown(ctx context.Context) (err error)

Shutdown stops the HTTP server.

func (*Runner) Start

func (r *Runner) Start(addr string, tlsFiles ...string) *Runner

Start starts a HTTP server with addr and ends when the server is closed.

If tlsFiles is not nil, it must be certFile and keyFile. For example,

runner := NewRunner()
runner.Start(":80", certFile, keyFile)

func (*Runner) Stop

func (r *Runner) Stop()

Stop is the same as r.Shutdown(context.Background()).

func (*Runner) Wait

func (r *Runner) Wait()

Wait waits until all the registered shutdown functions have finished.

type Ship

type Ship struct {
	*Runner

	/// Context
	CtxDataSize int // The initialization size of Context.Data.

	/// Route, Handler and Middleware
	Prefix           string
	NotFound         Handler
	RouteFilter      RouteFilter
	RouteModifier    RouteModifier
	MethodMapping    map[string]string // The default is DefaultMethodMapping.
	MiddlewareMaxNum int               // Default is 256

	// Others
	Logger      Logger
	Binder      binder.Binder
	Session     session.Session
	Renderer    render.Renderer
	BindQuery   func(interface{}, url.Values) error
	Responder   func(c *Context, args ...interface{}) error
	HandleError func(c *Context, err error)
	// contains filtered or unexported fields
}

Ship is an app to be used to manage the router.

func Default

func Default() *Ship

Default returns a new ship with default configuration, which will set Binder, Renderer and BindQuery to MuxBinder, MuxRenderer and BindURLValues based on New().

func New

func New() *Ship

New returns a new Ship.

func (*Ship) AcquireBuffer

func (s *Ship) AcquireBuffer() *bytes.Buffer

AcquireBuffer gets a Buffer from the pool.

func (*Ship) AcquireContext

func (s *Ship) AcquireContext(r *http.Request, w http.ResponseWriter) *Context

AcquireContext gets a Context from the pool.

func (*Ship) AddRoute added in v2.3.0

func (s *Ship) AddRoute(ri RouteInfo)

AddRoute registers the route, which uses the global middlewares to wrap the handler. If you don't want to use any middleware, you can do it by

s.Group("").NoMiddlewares().AddRoutes(ri)

Notice: "Name" and "Host" are optional, "Router" will be ignored. and others are mandatory.

func (*Ship) AddRoutes added in v2.3.0

func (s *Ship) AddRoutes(ris ...RouteInfo)

AddRoutes registers a set of the routes.

func (*Ship) Clone

func (s *Ship) Clone() *Ship

Clone clones itself to a new one without routes, middlewares and the server. Meanwhile, it will reset the signals of the new Ship to nil.

func (*Ship) Group

func (s *Ship) Group(prefix string) *RouteGroup

Group returns a new sub-group.

func (*Ship) Host

func (s *Ship) Host(host string) *RouteGroup

Host returns a new sub-group with the virtual host.

func (*Ship) NewContext

func (s *Ship) NewContext() *Context

NewContext news a Context.

func (*Ship) Pre

func (s *Ship) Pre(middlewares ...Middleware) *Ship

Pre registers the Pre-middlewares, which are executed before finding the route. then returns the origin ship router to write the chained router.

func (*Ship) R

func (s *Ship) R(path string) *Route

R is short for Route(path).

func (*Ship) ReleaseBuffer

func (s *Ship) ReleaseBuffer(buf *bytes.Buffer)

ReleaseBuffer puts a Buffer into the pool.

func (*Ship) ReleaseContext

func (s *Ship) ReleaseContext(c *Context)

ReleaseContext puts a Context into the pool.

func (*Ship) Route

func (s *Ship) Route(path string) *Route

Route returns a new route, then you can customize and register it.

You must call Route.Method() or its short method.

func (*Ship) Routers

func (s *Ship) Routers() map[string]router.Router

Routers returns the routers with their host.

For the main router, the host is "".

func (*Ship) Routes

func (s *Ship) Routes() []RouteInfo

Routes returns the inforatiom of all the routes.

func (*Ship) ServeHTTP

func (s *Ship) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the interface http.Handler.

func (*Ship) SetBufferSize

func (s *Ship) SetBufferSize(size int) *Ship

SetBufferSize resets the size of the buffer.

func (*Ship) SetLogger

func (s *Ship) SetLogger(logger Logger) *Ship

SetLogger sets the logger of Ship and Runner to logger.

func (*Ship) SetNewRouter

func (s *Ship) SetNewRouter(f func() router.Router) *Ship

SetNewRouter resets the NewRouter to create the new router.

It must be called before adding any route.

func (*Ship) URL

func (s *Ship) URL(name string, params ...interface{}) string

URL generates an URL from route name and provided parameters.

func (*Ship) URLParamsMaxNum

func (s *Ship) URLParamsMaxNum() int

URLParamsMaxNum reports the maximum number of the parameters of all the URLs.

Notice: it should be only called after adding all the urls.

func (*Ship) Use

func (s *Ship) Use(middlewares ...Middleware) *Ship

Use registers the global middlewares and returns the origin ship router to write the chained router.

Directories

Path Synopsis
Package middleware is the collection of the middlewares.
Package middleware is the collection of the middlewares.
Package router supplies some the builtin implementation about Router.
Package router supplies some the builtin implementation about Router.
echo
Package echo supplies a Router implementation based on github.com/labstack/echo.
Package echo supplies a Router implementation based on github.com/labstack/echo.

Jump to

Keyboard shortcuts

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