gohttprouter

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

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

Go to latest
Published: Sep 5, 2019 License: Apache-2.0 Imports: 6 Imported by: 0

README

go-httprouter

Build Status GoDoc Go Report Card

轻量级高性能HTTP路由框架(底层存储由基数树实现)(持续更新)

High-performance HTTP request router based on Go language

Usage

package main

import (
	"fmt"
	g "github.com/spider1998/go-httprouter"
	`log`
	"net/http"
	`testing`
)

func Index(w http.ResponseWriter, r *http.Request, ps g.Params) {
	_, _ = fmt.Fprint(w, "Welcome!\n")
}

func Hello(w http.ResponseWriter, r *http.Request, ps g.Params) {
	_, _ = fmt.Fprint(w, "Hello World!\n")
}

func Print(w http.ResponseWriter, r *http.Request, ps g.Params) {
	_, _ = fmt.Fprint(w, "++++++++++++++++Hello World!\n")
}

func Print11(w http.ResponseWriter, r *http.Request, ps g.Params) {
	_, _ = fmt.Fprint(w, "111111111111111111111111!\n")
}

func Print22(w http.ResponseWriter, r *http.Request, ps g.Params) {
	_, _ = fmt.Fprint(w, "22222222222222222222222222!\n")
}

func TestRouterGroup(t *testing.T) {
	router := g.New()
	test1 := router.Group("/test1",1)
	test1.GET("/index", Index,Print)
	test2 := router.Group("/test2",2)
	test2.GET("/hello", Hello)

	tes11:= test1.Group("/aaa",11)
	tes11.GET("/index",Print11)
	tes12:= test1.Group("/bbb",12)
	tes12.GET("/index",Print22)


	log.Println("start run...")
	log.Fatal(http.ListenAndServe(":8080", router))
}

Documentation

Overview

Package gohttprouter 提供路由处理存储

Package gohttprouter 提供简单http路由

Index

Constants

This section is empty.

Variables

View Source
var AllowAll = Options{
	AllowOrigins: "*",
	AllowHeaders: "*",
	AllowMethods: "*",
}

AllowAll is the option that allows all origins, headers, and methods.

View Source
var ParamsKey = paramsKey{}

ParamsKey 参数key

Functions

This section is empty.

Types

type Handler

type Handler func(http.ResponseWriter, *http.Request, Params)

Handler 路由处理函数

type LeafNode

type LeafNode struct {
	Key   string
	Value interface{}
}

LeafNode 叶子节点

type Node

type Node struct {
	Leaf   *LeafNode
	Prefix string
	Sons   Sons
}

Node 节点

type Options

type Options struct {
	// the allowed origins (separated by commas). Use an asterisk (*) to indicate allowing all origins, "null" to indicate disallowing any.
	AllowOrigins string
	// whether the response to request can be exposed when the omit credentials flag is unset, or whether the actual request can include user credentials.
	AllowCredentials bool
	// the HTTP methods (separated by commas) that can be used during the actual request. Use an asterisk (*) to indicate allowing any method.
	AllowMethods string
	// the HTTP headers (separated by commas) that can be used during the actual request. Use an asterisk (*) to indicate allowing any header.
	AllowHeaders string
	// the HTTP headers (separated by commas) that are safe to expose to the API of a CORS API specification
	ExposeHeaders string
	// Max amount of seconds that the results of a preflight request can be cached in a preflight result cache.
	MaxAge time.Duration
	// contains filtered or unexported fields
}

Options specifies how the CORS handler should respond with appropriate CORS headers.

type Param

type Param struct {
	Key   string
	Value string
}

Param 路由处理参数(暂留)

type Params

type Params []Param

Params 参数集合

type Router

type Router struct {
	RouterGroup            *RouterGroup
	Prefix                 string
	Trees                  map[string]*Tree
	PanicHandler           func(http.ResponseWriter, *http.Request)
	NotFound               http.Handler
	PathSlash              bool
	UseEscapedPath         bool
	HandleOptions          bool
	HandleMethodNotAllowed bool
	MethodNotAllowed       http.Handler
	HandlerIndex           int
	Handlers               []Handler
	Data                   map[string]interface{}
}

Router 路由结构体

func New

func New() *Router

New 创建新的路由

router := g.New()

返回路由实例

func (*Router) Abort

func (r *Router) Abort()

Abort 跳过其余处理程序

func (*Router) Cors

func (r *Router) Cors(opts Options) Handler

Cors Handler creates a routing handler that adds appropriate CORS headers according to the specified options and the request.

func (*Router) DELETE

func (r *Router) DELETE(path string, handlers ...Handler)

DELETE delete方法

func (*Router) GET

func (r *Router) GET(path string, handlers ...Handler)

GET get方法

router.GET("/", Index)

以下方法类似

func (*Router) GetData

func (r *Router) GetData(key string) interface{}

GetData 获取上下文存储的数据

func (*Router) Group

func (r *Router) Group(prefix string, level int) *Router

Group group分组方法

router.Group("/test1",1)

分组时第一个参数为组的路由前缀,第二个参数为组的层级,比如:第一个分组层级为1,第二个则为2, 第一个分组下面在进行分组,层级为11,12,13以此类推,第二个分组下面在进行分组,层级为21,22,23以此类推,

func (*Router) GroupUse

func (r *Router) GroupUse(level int, handlers ...Handler) *Router

GroupUse use路由预处理函数

router.Use(1,Print11,Print22)
test1 := router.Group("/test1", 1)
test1.Use(11,Print11)
test1.GET("/index", Index, Print)

第一个参数为路由组层级,与Group类似,可多级关联,执行当前组预处理函数时必须通过其父级预处理函数组

func (*Router) HEAD

func (r *Router) HEAD(path string, handlers ...Handler)

HEAD head方法

func (*Router) Handle

func (r *Router) Handle(method, path string, handles []Handler)

Handle 处理路由函数

r.Handle("GET", path, handles)

存储路由

func (*Router) Handler

func (r *Router) Handler(method, path string, handler http.Handler)

Handler is an adapter which allows the usage of an http.Handler as a request handle. With go 1.7+, the Params will be available in the request context under ParamsKey.

func (*Router) HandlerFunc

func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc)

HandlerFunc 内置处理函数

func (*Router) HandlerNext

func (r *Router) HandlerNext(w http.ResponseWriter, req *http.Request)

HandlerNext Next调用与当前路由关联的其余处理程序

func (*Router) OPTIONS

func (r *Router) OPTIONS(path string, handlers ...Handler)

OPTIONS options方法

func (*Router) PATCH

func (r *Router) PATCH(path string, handlers ...Handler)

PATCH patch方法

func (*Router) POST

func (r *Router) POST(path string, handlers ...Handler)

POST post方法

func (*Router) PUT

func (r *Router) PUT(path string, handlers ...Handler)

PUT put方法

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP 实现ServeHTTP方法

func (*Router) SetData

func (r *Router) SetData(key string, value interface{})

SetData 将信息存储在上下文中,以便以后检索

type RouterGroup

type RouterGroup struct {
	Groups   map[int]string
	Handlers map[int][]Handler
}

RouterGroup 路由组

func NewGroup

func NewGroup() *RouterGroup

NewGroup 创建新路由组

func (*RouterGroup) HandlerGenerate

func (r *RouterGroup) HandlerGenerate(index int) (handlers []Handler)

HandlerGenerate 获取路由组所有指定执行的方法

func (*RouterGroup) HandlerInsert

func (r *RouterGroup) HandlerInsert(index int, handlers ...Handler)

HandlerInsert 加入路由组处理方法

func (*RouterGroup) PrefixGenerate

func (r *RouterGroup) PrefixGenerate(index int) (path string)

PrefixGenerate 生成路由组前缀

func (*RouterGroup) PrefixInsert

func (r *RouterGroup) PrefixInsert(index int, prefix string)

PrefixInsert 加入路由组前缀

type Son

type Son struct {
	Label byte
	Node  *Node
}

Son 子节点

type Sons

type Sons []Son

Sons 子节点集合

func (Sons) Len

func (s Sons) Len() int

Len 获取长度

func (Sons) Less

func (s Sons) Less(i, j int) bool

Less 比较大小

func (Sons) Sort

func (s Sons) Sort()

Sort 排序

func (Sons) Swap

func (s Sons) Swap(i, j int)

Swap 交换值

type Tree

type Tree struct {
	Root *Node
	Size int
}

Tree 存储实体结构

func NewTree

func NewTree() *Tree

NewTree 创建树

func (*Tree) AddRoute

func (t *Tree) AddRoute(path string, handlers []Handler)

AddRoute 添加路由

func (*Tree) Get

func (t *Tree) Get(s string) (interface{}, bool)

Get 通过路由获取处理函数

if handles, _ := root.Get(path); handles != nil {
		for _, handle := range handles.([]Handle) {
			handle(w, req, nil)
		}
		return
	}

返回接口类型

func (*Tree) Insert

func (t *Tree) Insert(key string, value interface{}) (interface{}, bool)

Insert 存储路由处理信息

t.Insert(path, handles)

基数树

Jump to

Keyboard shortcuts

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