分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

Golang自带的http包的路由规则问题

发布时间:2023-09-06 01:22责任编辑:赖小花关键词:http
1、调用下面的方法开启一个http监听服务
http.HandleFunc("/hello/", helloHandler)
err := http.ListenAndServe(":8080", nil)
if err= nil {
??log.Fatal("ListenAndServe: ", err.Error())
}
2、路由规则中新增了"/hello"和"/hello/"两个key对应的handler(helloHandler)
3、跟踪http\server.go源码查看到路由匹配规则中,通过高亮的代码可以让我们分析出来,
假如我们请求路由"/hello/beijing",那么"/hello/"会被匹配到,但是这个通常不是我们想要的,
如果使用原生的http包路由规则为了避免这种情况,在注册路由的时候不要以"/"结尾,即注册"/hello"而不是"/hello/"
func pathMatch(pattern, path string) bool {
??if len(pattern) == 0 {
?????// should not happen
?????return false
??}
??n := len(pattern)
??if pattern[n-1] != ‘/‘ {
?????return pattern == path
??}
??return len(path) >= n && path[0:n] == pattern
}
 

Golang自带的http包的路由规则问题

原文地址:http://www.cnblogs.com/cythical-l-zc/p/7779383.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved