Golang-HTTP动态路由

在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)
}

猜你喜欢

转载自blog.csdn.net/mryang125/article/details/114004937