当前位置: 首页 > news >正文

go 1.22 增强 http.ServerMux 路由能力

之前

server

func main() {http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {fmt.Println("Received request:", r.URL.Path)fmt.Fprintf(w, "Hello, client! You requested: %s\n", r.URL.Path)})log.Println("Server is running on http://localhost:8080")if err := http.ListenAndServe(":8080", nil); err != nil {log.Fatal("ListenAndServe error: ", err)}
}

client

func main() {url := "http://localhost:8080/some-path"// 创建HTTP GET请求resp, err := http.Get(url)if err != nil {log.Fatal("HTTP GET error: ", err)}defer resp.Body.Close()// 读取响应体body, err := ioutil.ReadAll(resp.Body)if err != nil {log.Fatal("Error reading response body: ", err)}fmt.Println("Response from server:", string(body))
}

模式匹配优先级

如果两个模式重叠,那么更精确的模式优先。

如果 P1 符合 P2 请求的一个(严格)子集,P1 就比 P2 更精细
如果两者都不更具体,那么模式就会发生冲突

例外:
如果两个模式发生冲突,而其中一个有 HOST ,另一个没有,那么有 HOST 的模式优先。
在这里插入图片描述

example.com/ 比 / 更精细
因为第一个仅匹配主机 example.com 的请求,而第二个匹配任何请求

GET / 比 / 更精细
因为第一个仅匹配 GET 和 HEAD 请求,而第二个匹配任何请求

/b/{bucket}/o/default 比 /b/{bucket}/o/{noun} 更精细
第一个仅匹配第四个元素是文字 “default” 的路径,而在第二个中,第四个元素可以是任何内容

匹配方法

模式匹配将支持以 HTTP 方法开头,后跟空格,如 GET /demo 或 GET demo.com/ 中
带有方法的模式仅用于匹配具有该方法的请求

Go1.22 起,http.ServeMux 可以这么写:

mux.HandleFunc("POST /demo/create", func(w http.ResponseWriter, r *http.Request) {fmt.Fprint(w, "demo create")
})mux.HandleFunc("GET /demo/update", func(w http.ResponseWriter, r *http.Request) {fmt.Fprint(w, "demo update")
})

通配符

模式匹配将支持 {name} 或 {name…}
例如:/b/{bucket}/o/{objectname…}

该名称必须是有效的 Go 标识符和符合完整路径元素的标准
它们前面必须有斜杠,后面必须有斜杠或字符串末尾

例如:/b_{bucket} 不是有效的通配模式

Go1.22 起,http.ServeMux 可以这么写:

mux.HandleFunc("/demo/{id}", func(w http.ResponseWriter, r *http.Request) {id := r.PathValue("id")fmt.Fprint(w, "id %s", id)
})mux.HandleFunc("/demo/{path...}", func(w http.ResponseWriter, r *http.Request) {path := r.PathValue("path")fmt.Fprint(w, "path %s", path)
})

示例

server

func main() {http.HandleFunc("/demo/{id}", func(w http.ResponseWriter, r *http.Request) {id := r.PathValue("id")fmt.Fprintf(w, "id %s\n", id)fmt.Fprintf(w, "Hello, client! You requested: %s\n", r.URL.Path)})log.Println("Server is running  on /demo/x")if err := http.ListenAndServe(":8080", nil); err != nil {log.Fatal("ListenAndServe error: ", err)}
}

client

func client() {url := "http://localhost:8080/demo/2?name=cucc"// 创建HTTP GET请求resp, err := http.Get(url)if err != nil {log.Fatal("HTTP GET error: ", err)}defer resp.Body.Close()// 读取响应体body, err := ioutil.ReadAll(resp.Body)if err != nil {log.Fatal("Error reading response body: ", err)}fmt.Println("Response from server:\n", string(body))
}
http://www.lryc.cn/news/375195.html

相关文章:

  • 赶紧收藏!2024 年最常见 20道设计模式面试题(二)
  • Java面向对象设计 - Java泛型约束
  • 什么是内存泄漏?如何避免内存泄漏?
  • 元组(tuple)(Python)
  • 【C++进阶学习】第二弹——继承(下)——挖掘继承深处的奥秘
  • LangChain-ChatGLM本地搭建|报错合集(win10)
  • IP地址简介
  • 谈吐的艺术
  • Linux 和 分区
  • ⭐ ▶《强化学习的数学原理》(2024春)_西湖大学赵世钰 Ch3 贝尔曼最优公式 【压缩映射定理】
  • Pikachu上的CSRF以及NSSCTF上的[NISACTF 2022]bingdundun~、 [SWPUCTF 2022 新生赛]xff
  • 大数据分析-二手车用户数据可视化分析
  • AI训练Checkpoint对存储的影响
  • Python笔记 - 正则表达式
  • 安卓网络通信(多线程、HTTP访问、图片加载、即时通信)
  • Virtual Memory Primitives for User Program翻译
  • 网络基础2
  • C# 下载文件2
  • Unity | Tilemap系统
  • CSS选择符和可继承属性
  • C++升级软件时删除老版本软件的桌面快捷方式(附源码)
  • github国内加速访问有效方法
  • 如何处理JavaScript中的浮点数精度问题
  • ASPICE标准与ASPICE认证:提升汽车软件开发质量与效率的关键途径
  • easyexcel的简单使用(execl模板导出)
  • 代码随想录算法训练营第39天|● 62.不同路径 ●63. 不同路径 II
  • 【DevOps】 什么是容器 - 一种全新的软件部署方式
  • 使用pnpm创建vue3项目
  • 【软件测试】43个功能测试点总结
  • Python — — GPU编程