Golang-HTTP动态路由

本文介绍了如何利用Gorilla/Mux库在Go语言中实现RESTful API的不同请求方法处理、请求转发、HTTPS与HTTP请求差异化处理以及子路由转发。通过示例代码详细展示了如何配置路由,包括创建、读取、更新和删除操作,请求转发到不同服务器,以及根据请求协议和路径前缀匹配不同处理函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Restful服务中,我们可能期望实现这样的需求。

  • 接口路径相同,但是根据不同的请求方式,进行不同的处理请求
  • 将某个路径的请求转发到另一条主机
  • 将 https 和 http 请求交给不同的handler处理
  • 根据路径前缀匹配不同的子路由,转发给不同handler处理

强大的gorilla/mux即可实现这些需求

1. 根据请求方式不同进行路由

package main

import (
	"fmt"
	"net/http"

	"github.com/gorilla/mux"
)

func main() {
	r := mux.NewRouter()
	
	r.HandleFunc("/books/{title}", CreateBook).Methods("POST")
	r.HandleFunc("/books/{title}", ReadBook).Methods("GET")
	r.HandleFunc("/books/{title}", UpdateBook).Methods("PUT")
	r.HandleFunc("/books/{title}", DeleteBook).Methods("DELETE")
	
	http.ListenAndServe(":8080", r)
}

func CreateBook(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, "CreateBook: %v\n", vars["title"])
}

func ReadBook(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, "ReadBook: %v\n", vars["title"])
}

func UpdateBook(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, "UpdateBook: %v\n", vars["title"])
}

func DeleteBook(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, "DeleteBook: %v\n", vars["title"])
}

2. 请求转发

假设我们启动两个server,其中server1监听8081端口,server2监听8080端口。
server1:

func main() {
	http.HandleFunc("/", func (w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "Welcome to my website!")
	})
	http.ListenAndServe(":8081", nil)
}

server2:

func main() {
	r := mux.NewRouter()
	r.HandleFunc("/books/{title}", BookHandler).Host("localhost:8081")
	http.ListenAndServe(":8080", r)
}

由于server2中做了请求转发,对于/books/{title}的请求会转发到server1,所以访问http://localhost:8081/books/红楼梦才是有效的。

3. 对https和http请求分别处理

可以通过Schemes函数来区分请求是https还是http然后交给不同的handler处理。

func main() {
	r := mux.NewRouter()
	r.HandleFunc("/secure", SecureHandler).Schemes("https")
	r.HandleFunc("/insecure", InsecureHandler).Schemes("http")
	http.ListenAndServe(":8080", r)
}

4. 子路由转发

按照特定前缀匹配请求,对请求做子路由转发。如下,当请求为http://localhost:8080/books/,调用AllBooks函数。当请求为http://localhost:8080/books/红楼梦,调用GetBook函数。

func main() {
	r := mux.NewRouter()
	bookrouter := r.PathPrefix("/books").Subrouter()
	bookrouter.HandleFunc("/", AllBooks)
	bookrouter.HandleFunc("/{title}", GetBook)
	http.ListenAndServe(":8080", r)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alphathur

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值