小编Nuw*_*ika的帖子

如何使用golang杜松子酒为restful API创建身份验证模型?

我希望为我的restful API创建一个身份验证模型.希望使用API​​令牌,我在Web服务中使用MVC,我创建了一个这样的auth.go控制器.

package controllers

import (

    "github.com/gin-gonic/gin"
    "os"
    //"github.com/jinzhu/gorm"

)

type AdsControllerAuth struct {

}


func (ac *AdsControllerAuth)TokenAuthMiddleware gin.HandlerFunc {
  return func(c *gin.Context) {
    token := c.Request.FormValue("api_token")

    if token == "" {
      respondWithError(401, "API token required", c)
      return 
    }

    if token != os.Getenv("API_TOKEN") {
      respondWithError(401, "Invalid API token", c)
      return
    }

    c.Next()
  }
}

func respondWithError(code int,message string,c *gin.Context) {
  resp := map[string]string{"error": message}

  c.JSON(code, resp)
  //c.Abort(code)
}
Run Code Online (Sandbox Code Playgroud)

它目前无法正常工作,有人可以帮助这样做,还是有任何例子可以参考?

restful-authentication go go-gin

1
推荐指数
1
解决办法
5249
查看次数

标签 统计

go ×1

go-gin ×1

restful-authentication ×1