1. 程式人生 > >Go語言 如何使用gin框架的中介軟體做身份驗證~~~

Go語言 如何使用gin框架的中介軟體做身份驗證~~~

學習前提,對如何使用gin框架做基本的web服務有一個基本的認知~

server.go

package main

import (
"github.com/gin-gonic/gin"
"net/http"
)


func main(){
  router:=gin.Default()
  router.Use(Validate())  //使用validate()中介軟體身份驗證
  router.GET("/",Service1)
  router.Run(":8989")  //localhost:8989/
}

func Service1(c *gin.Context){
   c.JSON(http.StatusOK
,gin.H{"message":"你好,歡迎你"}) } func Validate() gin.HandlerFunc{ return func(c *gin.Context){ //這一部分可以替換成從session/cookie中獲取, username:=c.Query("username") password:=c.Query("password") if username=="ft" && password =="123"{ c.JSON(http.StatusOK,gin.H{"message":"身份驗證成功"}) c.Next
() //該句可以省略,寫出來只是表明可以進行驗證下一步中介軟體,不寫,也是內建會繼續訪問下一個中介軟體的 }else { c.Abort() c.JSON(http.StatusUnauthorized,gin.H{"message":"身份驗證失敗"}) return// return也是可以省略的,執行了abort操作,會內建在中介軟體defer前,return,寫出來也只是解答為什麼Abort()之後,還能執行返回JSON資料 } } }

client.go

package main

import (
    "fmt"
    "io/ioutil"
"net/http" ) func main() { var resp *http.Response resp, _ = http.Get("http://10.0.203.92:8989?username=ft2&&password=123") // resp, _ = http.Get("http://10.0.203.92:8989?username=ft&&password=123") helpRead(resp) } func helpRead(resp *http.Response) { defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("ERROR2!: ", err) } fmt.Println(string(body)) }

工程架構圖:
這裡寫圖片描述

使用git直接分別在client.go和server.go路徑目錄下右鍵git bash here,需要安裝git
git server.go
這裡寫圖片描述

git client.go 和 server git的響應如下
這裡寫圖片描述

正確的使用者是ft 123
當輸入ft2 123,歡迎的服務頁面被攔截