代码示例:
package main
import (
"encoding/json"
"github.com/gorilla/mux"
"net/http"
)
// 定义Product的结构体
type Product struct {
Name string `json:"name"`
Price float64 `json:"price"`
Num int32
Desc string
}
// 定义Shop的结构体
type Shop struct {
Name string `json:"name"`
Address string `json:"address"`
}
// 初始化Product和Shop的切片
var productlist []Product
var shoplist []Shop
// 获取Product列表
func getProductListHandler(w http.ResponseWriter, r *http.Request) {
// Header设置Content-Type为json格式,输出json格式的结果,看起来更方便
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(productlist)
}
// 获取Shop列表
func getShopListHandler(w http.ResponseWriter, r *http.Request) {
// Header设置Content-Type为json格式,输出json格式的结果,看起来更方便
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(shoplist)
}
func main() {
// 初始化ProductList的数据
productlist = append(productlist, Product{Name: "地球仪", Price: 10, Num: 102, Desc: "世界地球仪,360度旋转"})
productlist = append(productlist, Product{Name: "鱼缸", Price: 28.8, Num: 2, Desc: "长50cm,宽28cm,高60cm"})
// 初始化ShopList的数据
shoplist = append(shoplist, Shop{Name: "苹果太古里店", Address: "成都太古里"})
shoplist = append(shoplist, Shop{Name: "优衣库三里屯店", Address: "北京三里屯"})
// 初始化一个新的路由
r := mux.NewRouter()
// Product的子路由
p := r.PathPrefix("/products").Subrouter()
p.HandleFunc("/list", getProductListHandler).Methods("GET")
// Shop的子路由
s := r.PathPrefix("/shop").Subrouter()
s.HandleFunc("/list", getShopListHandler).Methods("GET")
// 监听8001端口
http.ListenAndServe(":8001", r)
}
运行程序,通过postman或其它http请求工具发送请求,下面是测试的结果。
1、GET请求http://localhost:8001/products/list,结果:
[
{
"name": "地球仪",
"price": 10,
"Num": 102,
"Desc": "世界地球仪,360度旋转"
},
{
"name": "鱼缸",
"price": 28.8,
"Num": 2,
"Desc": "长50cm,宽28cm,高60cm"
}
]
2、GET请求http://localhost:8001/shop/list,结果:
[
{
"name": "苹果太古里店",
"address": "成都太古里"
},
{
"name": "优衣库三里屯店",
"address": "北京三里屯"
}
]
以上就是mux子路由的基本使用,git地址:https://gitee.com/sunzf/test-go/blob/master/src/mux/testSubrouter.go