mux路由中间件的使用

mux路由中间件的使用

代码示例:

package main

import (
    "encoding/json"
    "fmt"
    "github.com/gorilla/mux"
    "net/http"
    "strings"
)

// 定义Fish的结构体
type Fish struct {
    Name string `json:"name"`
}

var fishlist []Fish

// 获取Fish列表
func getFishListHandler(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(fishlist)
}

func logMiddleware(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // 打印请求路径
        fmt.Println(r.RequestURI)
        //fmt.Fprintln(w, "%s\r\n", r.URL)
        h.ServeHTTP(w, r)
    })
}

// 定义权限的中间件结构体
type AuthMiddleware struct {
    token map[string]string
}

func (amw *AuthMiddleware) Populate() {
    amw.token = make(map[string]string)
    amw.token["000"] = "user0"
    amw.token["aaa"] = "userA"
    amw.token["05ft"] = "randomUser"
    amw.token["deadbeef"] = "user0"
}

func (amw *AuthMiddleware) authMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        token := strings.Trim(r.Header.Get("X-Session-Token"), " ")
        if token == "" {
            fmt.Fprintf(w, "token is error \r\n")
        }

        if user, found := amw.token[token]; found {
            //we found the token in out map
            fmt.Printf("Authenticated user: %s\n", user)
            fmt.Fprintf(w, "Authenticated user: %s\n", user)
            // Pass down the request to the next middleware (or final handler)
            next.ServeHTTP(w, r)
        } else {
            // Write an error and stop the handler chain
            http.Error(w, "Forbidden", http.StatusForbidden)
        }
    })
}

func main() {
    // 初始化fishlist的数据
    fishlist = append(fishlist, Fish{Name: "金鱼"})
    fishlist = append(fishlist, Fish{Name: "鲤鱼"})

    // 初始化一个新的路由
    r := mux.NewRouter()
    r.HandleFunc("/fish/list", getFishListHandler).Methods("GET")

    // 使用中间件
    //r.Use(logMiddleware)
    amw := AuthMiddleware{}
    amw.Populate()

    r.Use(amw.authMiddleware)

    // 监听8002端口
    http.ListenAndServe(":8002", r)
}

运行程序,通过postman或其它http请求工具发送请求,下面是测试的结果。

1、GET请求:http://localhost:8002/fish/list,headers不加参数,直接请求返回:
token is error 
Forbidden
2、GET请求:http://localhost:8002/fish/list,headers增加X-Session-Token:000,结果:
Authenticated user: user0
[{"name":"金鱼"},{"name":"鲤鱼"}]
image.png
3、GET请求:http://localhost:8002/fish/list,headers增加X-Session-Token:0000(或者随便输入),结果:(返回状态为403)
Forbidden
git地址:https://gitee.com/sunzf/test-go/blob/master/src/mux/testMiddleware.go
参考: https://www.cnblogs.com/jiujuan/p/12768907.html

你可能感兴趣的:(mux路由中间件的使用)