Golang中HttpRouter路由的使用详解
作者:技术颜良 发布时间:2024-04-30 10:04:23
httprouter
httprouter 是一个高性能、可扩展的HTTP路由,上面我们列举的net/http默认路由的不足,都被httprouter 实现,我们先用一个例子,认识下 httprouter 这个强大的 HTTP 路由。
安装:
go get -u github.com/julienschmidt/httprouter
在这个例子中,首先通过httprouter.New()生成了一个*Router路由指针,然后使用GET方法注册一个适配/路径的Index函数,最后*Router作为参数传给ListenAndServe函数启动HTTP服务即可。
package main
import (
"log"
"net/http"
"github.com/julienschmidt/httprouter"
)
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
w.Write([]byte("Index"))
}
func main() {
router := httprouter.New()
router.GET("/", Index)
log.Fatal(http.ListenAndServe(":8080", router))
}
httprouter 为所有的HTTP Method 提供了快捷的使用方式,只需要调用对应的方法即可。
func (r *Router) GET(path string, handle Handle) {
r.Handle("GET", path, handle)
}
func (r *Router) HEAD(path string, handle Handle) {
r.Handle("HEAD", path, handle)
}
func (r *Router) OPTIONS(path string, handle Handle) {
r.Handle("OPTIONS", path, handle)
}
func (r *Router) POST(path string, handle Handle) {
r.Handle("POST", path, handle)
}
func (r *Router) PUT(path string, handle Handle) {
r.Handle("PUT", path, handle)
}
func (r *Router) PATCH(path string, handle Handle) {
r.Handle("PATCH", path, handle)
}
func (r *Router) DELETE(path string, handle Handle) {
r.Handle("DELETE", path, handle)
}
现代的API,基本上都是Restful API,httprouter提供的命名参数的支持,可以很方便的帮助我们开发Restful API。比如我们设计的API/user/flysnow,这这样一个URL,可以查看flysnow这个用户的信息,如果要查看其他用户的,比如zhangsan,我们只需要访问API/user/zhangsan即可。
URL包括两种匹配模式:/user/:name精确匹配、/user/*name匹配所有的模式。
package main
import (
"github.com/julienschmidt/httprouter"
"net/http"
"log"
"fmt"
)
func main() {
router:=httprouter.New()
router.GET("/MainData", func (w http.ResponseWriter,r *http.Request,_ httprouter.Params) {
w.Write([]byte("default get"))
})
router.POST("/MainData",func (w http.ResponseWriter,r *http.Request,_ httprouter.Params) {
w.Write([]byte("default post"))
})
//精确匹配
router.GET("/user/name",func (w http.ResponseWriter,r *http.Request,p httprouter.Params) {
w.Write([]byte("user name:"+p.ByName("name")))
})
//匹配所有
router.GET("/employee/*name",func (w http.ResponseWriter,r *http.Request,p httprouter.Params) {
w.Write([]byte("employee name:"+p.ByName("name")))
})
http.ListenAndServe(":8081", router)
}
Handler处理链处理不同二级域名
package main
import (
"fmt"
"log"
"net/http"
"github.com/julienschmidt/httprouter"
)
type HostMap map[string]http.Handler
func (hs HostMap) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Println("222")
//根据域名获取对应的Handler路由,然后调用处理(分发机制)
if handler := hs[r.Host]; handler != nil {
handler.ServeHTTP(w, r)
} else {
http.Error(w, "Forbidden", 403)
}
}
func main() {
userRouter := httprouter.New()
userRouter.GET("/", func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
w.Write([]byte("play"))
})
dataRouter := httprouter.New()
dataRouter.GET("/", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
w.Write([]byte("tool"))
})
//分别用于处理不同的二级域名
hs := make(HostMap)
hs["user.localhost:12345"] = userRouter
hs["data.localhost:12345"] = dataRouter
log.Fatal(http.ListenAndServe(":12345", hs))
}
httprouter提供了很方便的静态文件服务,可以把一个目录托管在服务器上,以供访问。
router.ServeFiles("/static/*filepath",http.Dir("./"))
使用ServeFiles需要注意的是,第一个参数路径,必须要以/*filepath,因为要获取我们要访问的路径信息。
func (r *Router) ServeFiles(path string, root http.FileSystem) {
if len(path) < 10 || path[len(path)-10:] != "/*filepath" {
panic("path must end with /*filepath in path '" + path + "'")
}
fileServer := http.FileServer(root)
r.GET(path, func(w http.ResponseWriter, req *http.Request, ps Params) {
req.URL.Path = ps.ByName("filepath")
fileServer.ServeHTTP(w, req)
})
}
例子:
package main
import (
"log"
"net/http"
"github.com/julienschmidt/httprouter"
)
func main() {
router := httprouter.New()
//访问静态文件
router.ServeFiles("/static/*filepath", http.Dir("./files"))
log.Fatal(http.ListenAndServe(":8080", router))
}
httprouter 异常捕获,httprouter允许使用者,设置PanicHandler用于处理HTTP请求中发生的panic。
package main
import (
"fmt"
"log"
"net/http"
"github.com/julienschmidt/httprouter"
)
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
panic("error")
}
func main() {
router := httprouter.New()
router.GET("/", Index)
//捕获异常
router.PanicHandler = func(w http.ResponseWriter, r *http.Request, v interface{}) {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "error:%s", v)
}
log.Fatal(http.ListenAndServe(":8080", router))
}
httprouter还有不少有用的小功能,比如对404进行处理,我们通过设置Router.NotFound来实现,我们看看Router这个结构体的配置,可以发现更多有用的功能。
type Router struct {
//是否通过重定向,给路径自定加斜杠
RedirectTrailingSlash bool
//是否通过重定向,自动修复路径,比如双斜杠等自动修复为单斜杠
RedirectFixedPath bool
//是否检测当前请求的方法被允许
HandleMethodNotAllowed bool
//是否自定答复OPTION请求
HandleOPTIONS bool
//404默认处理
NotFound http.Handler
//不被允许的方法默认处理
MethodNotAllowed http.Handler
//异常统一处理
PanicHandler func(http.ResponseWriter, *http.Request, interface{})
}
来源:https://www.cnblogs.com/cheyunhua/p/15545261.html


猜你喜欢
- 一、函数解释在torch/_C/_VariableFunctions.py的有该定义,意义就是实现一下公式:换句话说,就是需要传入5个参数,
- RSS 是一个可用多种扩展来表示的缩写:“RDF 站点摘要(RDF Site Summary)”、“真正简单的辛迪加(Really Simp
- 一、什么是数据库连接池就是一个容器持有多个数据库连接,当程序需要操作数据库的时候直接从池中取出连接,使用完之后再还回去,和线程池一个道理。二
- 如何用数据库制作一个多用户版的计数器?代码和说明如下:count.asp' 计数器的核心程序<%Set c
- 简介在php中,类型的继承使用extends关键字,而且最多只能继承一个父类,php不支持多继承。class MyClass {
- Python字符串处理学习中,有一道简单但很经典的题目,按照单词对字符串进行反转,并对原始空格进行保留: 如:‘ I love China!
- 关于正则表达式raw的\匹配规则这是我在学习中获得到的一个例子,第一表达式中匹配到的是none。于是乎我就在思考,为什么会匹配不到,假设\t
- ASP正则表达式,RegExp对象提供简单的正则表达式支持功能。RegExp对象的用法: Function RegExpTest(
- 如下所示:ljust(len,str)字符向左对齐,用str补齐长度rjust(len,str)字符向右对齐,用str补齐长度rjust(l
- 最近为数据库服务器增加了内存,达到了最大支持的8G,数据库用的是mssql 2005 ,之前内存一直是4G的,不存在内存大和32位操作系统冲
- Pandas DataFrame 取一行数据会得到Series的方法如题,想要取如下dataframe的一行数据,以为得到的还是datafr
- 对于array,如2-D的array,如何取指定元素设array为3*10的shapes = array([[ 0, 1, 2, 3, 4,
- 类型主要针对文本属性进行定义。理解“编辑字体列表”和“行高”。二、CSS规则定义之“背景”·背景有背景颜色和背景图像的选择设置。·利于背景图
- PHP session用法其实很简单它可以把用户提交的数据以全局变量形式保存在一个session中并且会生成一个唯一的session_id,
- 今天讲下软件开发中最常见的历史数据迁移方式。在讲迁移之前,先简单介绍下几个基本概念。1、什么是历史数据迁移?简单直白地说:就是将一些创建时间
- Git修改已提交的commit注释两种情况:修改最后一次注释1、在命令行输入如下命令,然后回车:git commit --amend2、在命
- 一、起源 因子分析的起源是这样的:1904年英
- 异常详细信息: System.Web.HttpException: 无法向会话状态服务器发出会话状态请求。请确保已启动 ASP.NET St
- Matplotlib 是 Python 的二维绘图库,用于生成符合出版质量或跨平台交互环境的各类图形。图形解析与工作流图形解析 工
- python 根据正则表达式提取指定的内容正则表达式是极其强大的,利用正则表达式来提取想要的内容是很方便的事。 下面演