Go语言HttpRouter路由使用方法详解
怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《Go语言HttpRouter路由使用方法详解》,涉及到路由,有需要的可以收藏一下
HttpRouter是一个轻量级但却非常高效的multiplexer。手册:
用法示例
package main import ( "fmt" "github.com/julienschmidt/httprouter" "net/http" "log" ) func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { fmt.Fprint(w, "Welcome!\n") } func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name")) } func main() { router := httprouter.New() router.GET("/", Index) router.GET("/hello/:name", Hello) log.Fatal(http.ListenAndServe(":8080", router)) }
首先执行:
go get github.com/julienschmidt/httprouter
然后再启动web服务:
go run xxx.go
和http包的ServeMux用法其实很类似。上面定义了两个httprouter中的handle,类似于http包中的http.HandlerFunc类型,具体的对应关系后文会解释,只要认为它是handler,是处理对应请求的就行了。然后使用New()方法创建了实例,并使用GET()方法为两个模式注册了对应的handler。
需要注意的是,第二个模式"/hello/:name",它可以用来做命名匹配,类似于正则表达式的命名捕获分组。后面会详细解释用法。
httprouter用法说明
Variables func CleanPath(p string) string type Handle type Param type Params func ParamsFromContext(ctx context.Context) Params func (ps Params) ByName(name string) string type Router func New() *Router func (r *Router) DELETE(path string, handle Handle) func (r *Router) GET(path string, handle Handle) func (r *Router) HEAD(path string, handle Handle) func (r *Router) Handle(method, path string, handle Handle) func (r *Router) Handler(method, path string, handler http.Handler) func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc) func (r *Router) Lookup(method, path string) (Handle, Params, bool) func (r *Router) OPTIONS(path string, handle Handle) func (r *Router) PATCH(path string, handle Handle) func (r *Router) POST(path string, handle Handle) func (r *Router) PUT(path string, handle Handle) func (r *Router) ServeFiles(path string, root http.FileSystem) func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
type Handle
httprouter中的Handle类似于http.HandlerFunc,只不过它支持第三个参数Params。
type Handle func(http.ResponseWriter, *http.Request, Params) Handle is a function that can be registered to a route to handle HTTP requests. Like http.HandlerFunc, but has a third parameter for the values of wildcards (variables).
例如前面示例中的Index()和Hello()都是Handle类型的实例。
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { fmt.Fprint(w, "Welcome!\n") } func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name")) }
注册handler
httprouter.Router类型类似于http包中的ServeMux,它实现了http.Handler接口,所以它是一个http.Handler。它可以将请求分配给注册好的handler。
type Router struct {} func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
除此之外,Router提供了不少方法,用来指示如何为路径注册handler。
func (r *Router) Handle(method, path string, handle Handle) func (r *Router) Handler(method, path string, handler http.Handler) func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc)
httprouter.Handle()用于为路径注册指定的Handle,而httprouter.Handle对应于http.HandlerFunc,所以是直接将Handle类型的函数绑定到指定路径上。同时,它还可以指定http方法:GET, POST, HEAD, PUT, PATCH, DELETE, OPTIONS。
这些方法还有对应的各自缩写:
func (r *Router) DELETE(path string, handle Handle) func (r *Router) GET(path string, handle Handle) func (r *Router) HEAD(path string, handle Handle) func (r *Router) OPTIONS(path string, handle Handle) func (r *Router) PATCH(path string, handle Handle) func (r *Router) POST(path string, handle Handle) func (r *Router) PUT(path string, handle Handle)
例如,Get()等价于route.Handle("GET", path, handle)。
例如上面的示例中,为两个路径注册了各自的httprouter.Handle函数。
router := httprouter.New() router.GET("/", Index) router.GET("/hello/:name", Hello)
Handler()方法是直接为指定http方法和路径注册http.Handler;HandlerFunc()方法则是直接为指定http方法和路径注册http.HandlerFunc。
Param相关
type Param struct { Key string Value string } Param is a single URL parameter, consisting of a key and a value. 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 (ps 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.
Param类型是key/value型的结构,每个分组捕获到的值都会保存为此类型。正如前面的示例中:
router.GET("/hello/:name", Hello)
这里的:name
就是key,当请求的URL路径为/hello/abc
,则key对应的value为abc。也就是说保存了一个Param实例:
Param{ Key: "name", Value: "abc", }
更多的匹配用法稍后解释。
Params是Param的slice。也就是说,每个分组捕获到的key/value都存放在这个slice中。
ByName(str)方法可以根据Param的Key检索已经保存在slice中的Param的Value。正如示例中:
func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name")) } router.GET("/hello/:name", Hello)
这里ByName("name")
将检索保存在slice中,Key="name"的Param,且返回这个Param中的Value。
由于Params是slice结构,除了ByName()方法可以检索key/value,通过slice的方法也可以直接检索:
ps[0].Key ps[0].Value
路径匹配规则
httprouter要为路径注册handler的适合,路径可以进行命名捕获。有两种命名捕获的方式:
Syntax Type :name named parameter *name catch-all parameter
其中:name
的捕获方式是匹配内容直到下一个斜线或者路径的结尾。例如要为如下路径注册handler:
Path: /blog/:category/:post
当请求路径为:
/blog/go/request-routers match: category="go", post="request-routers" /blog/go/request-routers/ no match, but the router would redirect /blog/go/ no match /blog/go/request-routers/comments no match
*name
的捕获方式是从指定位置开始(包含前缀"/")匹配到结尾:
Path: /files/*filepath /files/ match: filepath="/" /files/LICENSE match: filepath="/LICENSE" /files/templates/article.html match: filepath="/templates/article.html" /files no match, but the router would redirect
再解释下什么时候会进行重定向。在Router类型中,第一个字段控制尾随斜线的重定向操作:
type Router struct { RedirectTrailingSlash bool ... }
如果请求的URL路径包含或者不包含尾随斜线时,但在注册的路径上包含了或没有包含"/"的目标上定义了handler,但是会进行301重定向。简单地说,不管URL是否带尾随斜线,只要注册路径不存在,但在去掉尾随斜线或加上尾随斜线的路径上定义了handler,就会自动重定向。
例如注册路径为/foo
,请求路径为/foo/
,会重定向。
下面还有几种会重定向的情况:
注册路径:/blog/:category/:post 请求URL路径:/blog/go/request-routers/ 注册路径:/blog/:category 请求URL路径:/blog/go 注册路径:/files/*filepath 请求URL路径:/files
Lookup()
func (r *Router) Lookup(method, path string) (Handle, Params, bool)
Lookup根据method+path检索对应的Handle,以及Params,并可以通过第三个返回值判断是否会进行重定向。
更多关于Go语言HttpRouter路由使用方法详解请查看下面的相关链接
本篇关于《Go语言HttpRouter路由使用方法详解》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

- 上一篇
- Go语言Handler详细说明

- 下一篇
- Go语言学习之函数的定义与使用详解
-
- 朴素的蜡烛
- 这篇文章出现的刚刚好,太全面了,感谢大佬分享,已收藏,关注楼主了!希望楼主能多写Golang相关的文章。
- 2023-03-11 10:30:02
-
- 正直的彩虹
- 感谢大佬分享,一直没懂这个问题,但其实工作中常常有遇到...不过今天到这,帮助很大,总算是懂了,感谢楼主分享文章内容!
- 2023-02-27 05:33:45
-
- 威武的春天
- 太细致了,mark,感谢大佬的这篇博文,我会继续支持!
- 2023-02-23 20:34:36
-
- Golang · Go教程 | 17小时前 |
- TigervncDebian多用户共享桌面超简单教程
- 482浏览 收藏
-
- Golang · Go教程 | 1天前 |
- Go语言新手必看!切片vs数组,一次搞定这两个核心知识点
- 472浏览 收藏
-
- Golang · Go教程 | 1天前 |
- Docker在Debian上运行超简单教程(保姆级教学)
- 210浏览 收藏
-
- Golang · Go教程 | 1天前 |
- Debian设置hostname踩坑记录:权限问题大揭秘
- 334浏览 收藏
-
- Golang · Go教程 | 1天前 |
- Debian装SQLServer?这些问题你一定要注意!
- 284浏览 收藏
-
- Golang · Go教程 | 2天前 |
- Debian系统下Jenkins自动化部署脚本教学
- 367浏览 收藏
-
- Golang · Go教程 | 2天前 |
- DebianSwap服务器应用实测,这些场景真的用得上!
- 319浏览 收藏
-
- Golang · Go教程 | 2天前 |
- Debian跑TigerVNC实测!真香警告,快来看看性能咋样~
- 171浏览 收藏
-
- Golang · Go教程 | 2天前 |
- 在Debian上玩转SQLServer备份还原,手把手教你一步步操作
- 498浏览 收藏
-
- Golang · Go教程 | 2天前 |
- DebianOverlay不会玩?手把手教你轻松定制化安装
- 258浏览 收藏
-
- Golang · Go教程 | 2天前 |
- Go语言实战:time.Ticker&time.After用法区别及避坑技巧
- 240浏览 收藏
-
- Golang · Go教程 | 2天前 |
- Debian系统如何快速定位&干掉那些讨厌的僵尸进程
- 317浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 茅茅虫AIGC检测
- 茅茅虫AIGC检测,湖南茅茅虫科技有限公司倾力打造,运用NLP技术精准识别AI生成文本,提供论文、专著等学术文本的AIGC检测服务。支持多种格式,生成可视化报告,保障您的学术诚信和内容质量。
- 18次使用
-
- 赛林匹克平台(Challympics)
- 探索赛林匹克平台Challympics,一个聚焦人工智能、算力算法、量子计算等前沿技术的赛事聚合平台。连接产学研用,助力科技创新与产业升级。
- 50次使用
-
- 笔格AIPPT
- SEO 笔格AIPPT是135编辑器推出的AI智能PPT制作平台,依托DeepSeek大模型,实现智能大纲生成、一键PPT生成、AI文字优化、图像生成等功能。免费试用,提升PPT制作效率,适用于商务演示、教育培训等多种场景。
- 57次使用
-
- 稿定PPT
- 告别PPT制作难题!稿定PPT提供海量模板、AI智能生成、在线协作,助您轻松制作专业演示文稿。职场办公、教育学习、企业服务全覆盖,降本增效,释放创意!
- 53次使用
-
- Suno苏诺中文版
- 探索Suno苏诺中文版,一款颠覆传统音乐创作的AI平台。无需专业技能,轻松创作个性化音乐。智能词曲生成、风格迁移、海量音效,释放您的音乐灵感!
- 57次使用
-
- golang beego框架路由ORM增删改查完整案例
- 2022-12-30 456浏览
-
- 基于gin的golang web开发:路由示例详解
- 2023-01-07 390浏览
-
- golang利用不到20行代码实现路由调度详解
- 2022-12-23 245浏览
-
- Golang中的路由使用详解
- 2023-01-07 161浏览
-
- MySQL分库分表后路由策略设计详情
- 2022-12-31 257浏览