【go项目01_学习记录04】

学习记录

  • [1 集成 Gorilla Mux](#1 集成 Gorilla Mux)
    • [1.1 为什么不选择 HttpRouter?](#1.1 为什么不选择 HttpRouter?)
    • [1.2 安装 gorilla/mux](#1.2 安装 gorilla/mux)
    • [1.3 使用 gorilla/mux](#1.3 使用 gorilla/mux)
    • [1.4 迁移到 Gorilla Mux](#1.4 迁移到 Gorilla Mux)
      • [1.4.1 新增 homeHandler](#1.4.1 新增 homeHandler)
      • [1.4.2 指定 Methods () 来区分请求方法](#1.4.2 指定 Methods () 来区分请求方法)
      • [1.4.3 请求路径参数和正则匹配](#1.4.3 请求路径参数和正则匹配)
      • [1.4.4 命名路由与链接生成](#1.4.4 命名路由与链接生成)

1 集成 Gorilla Mux

1.1 为什么不选择 HttpRouter?

HttpRouter是目前最快的路由器,被知名GIN框架所采用。

没有选择HttpRouter是因为功能略显单一,没有由于命名功能。

HttpRouter和GIN比较适合性能要求高,路由功能相对简单的项目中,如API或微服务。在全站开发Web中,gorilla/mux功能更强大,比较实用。

1.2 安装 gorilla/mux

安装第三方依赖

复制代码
go get -u github.com/gorilla/mux

查看文件变更情况

复制代码
git status

两个文件变更

1.3 使用 gorilla/mux


1.4 迁移到 Gorilla Mux

改进main.go

go 复制代码
package main

import (
    "fmt"
    "net/http"

    "github.com/gorilla/mux"
)

func homeHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/html; charset=utf-8")
    fmt.Fprint(w, "<h1>Hello, 欢迎来到 goblog!</h1>")
}

func aboutHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/html; charset=utf-8")
    fmt.Fprint(w, "此博客是用以记录编程笔记,如您有反馈或建议,请联系 "+
        "<a href=\"mailto:summer@example.com\">summer@example.com</a>")
}

func notFoundHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/html; charset=utf-8")
    w.WriteHeader(http.StatusNotFound)
    fmt.Fprint(w, "<h1>请求页面未找到 :(</h1><p>如有疑惑,请联系我们。</p>")
}

func articlesShowHandler(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    id := vars["id"]
    fmt.Fprint(w, "文章 ID:"+id)
}

func articlesIndexHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "访问文章列表")
}

func articlesStoreHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "创建新的文章")
}

func main() {
    router := mux.NewRouter()

    router.HandleFunc("/", homeHandler).Methods("GET").Name("home")
    router.HandleFunc("/about", aboutHandler).Methods("GET").Name("about")

    router.HandleFunc("/articles/{id:[0-9]+}", articlesShowHandler).Methods("GET").Name("articles.show")
    router.HandleFunc("/articles", articlesIndexHandler).Methods("GET").Name("articles.index")
    router.HandleFunc("/articles", articlesStoreHandler).Methods("POST").Name("articles.store")

    // 自定义 404 页面
    router.NotFoundHandler = http.HandlerFunc(notFoundHandler)

    // 通过命名路由获取 URL 示例
    homeURL, _ := router.Get("home").URL()
    fmt.Println("homeURL: ", homeURL)
    articleURL, _ := router.Get("articles.show").URL("id", "23")
    fmt.Println("articleURL: ", articleURL)

    http.ListenAndServe(":3000", router)
}

1.4.1 新增 homeHandler

首先,因为使用的是精确匹配,我们将 defaultHandler 变更 homeHandler 且将处理 404 的代码移除。

1.4.2 指定 Methods () 来区分请求方法

curl测试

复制代码
curl http://localhost:3000/articles

curl -Method POST http://localhost:3000/articles

注意: 在 Gorilla Mux 中,如未指定请求方法,默认会匹配所有方法。

1.4.3 请求路径参数和正则匹配

go 复制代码
router.HandleFunc("/articles/{id:[0-9]+}", articlesShowHandler).Methods("GET").Name("articles.show")

Handler 中获取到这个参数:

go 复制代码
func articlesShowHandler(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    id := vars["id"]
    fmt.Fprint(w, "文章 ID:"+id)
}

1.4.4 命名路由与链接生成

air中显示打印结果


相关推荐
老赵的博客36 分钟前
QT的项目pro qmake编译
开发语言·qt
枯萎穿心攻击1 小时前
从 Unity UGUI 到 Unreal UMG 的交互与高效实践:UI 事件、坐标系适配与性能优化
开发语言·ui·unity·性能优化·ue5·游戏引擎·虚幻引擎
WALL-EC1 小时前
Qt工具栏中图标槽函数没有响应的问题分析
开发语言·qt·osgearth
red_redemption2 小时前
自由学习记录(87)
学习
熙客2 小时前
Java:HashMap的使用
java·开发语言
咸甜适中2 小时前
rust语言 (1.88) egui (0.32.1) 学习笔记(逐行注释)(十五)网格布局
笔记·学习·rust·egui
weixin_307779133 小时前
C++进程监视器与自动启动程序
开发语言·c++·算法
草莓熊Lotso3 小时前
【C语言强化训练16天】--从基础到进阶的蜕变之旅:Day12
c语言·开发语言·c++·刷题
不喜欢学数学er3 小时前
算法第五十三天:图论part04(第十一章)
开发语言·python·图论
你怎么知道我是队长3 小时前
python---构造函数、析构函数
开发语言·python