go>> gah>> 返回
项目作者: yasaricli

项目描述 :
Gin Auth Handlers
高级语言: Go
项目地址: git://github.com/yasaricli/gah.git
创建时间: 2020-01-03T18:56:10Z
项目社区:https://github.com/yasaricli/gah

开源协议:

下载


Gin Auth Handlers

Installation

To install Gah (Gin Auth Handlers) package, you need to install Go and set your Go workspace first.

dev.to
Authentication with gin-gonic && gah for golang

You can use the below Go command to install Gah.

  1. go get -u github.com/yasaricli/gah

Usage and documentation

First let’s set the required environment variables

  1. export MONGO_URL=mongodb://127.0.0.1:27017 # MongoDB server URL.
  2. export MONGO_DATABASE=project_db # MongoDB Project db name
  3. export MONGO_COLLECTION=users # Collection to register all users

Use with gin-gonic

You need the gin package to use gah. You can install it as follows.

  1. go get -u github.com/gin-gonic/gin

Add the LoginHandler and RegisterHandler functions to the API.

  1. package main
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/yasaricli/gah"
  5. )
  6. func main() {
  7. router := gin.Default()
  8. api := router.Group("/api")
  9. {
  10. api.POST("/login", gah.LoginHandler)
  11. api.POST("/register", gah.RegisterHandler)
  12. }
  13. router.Run(":4000")
  14. }

AuthRequiredMiddleware

Let’s make a handler where the user is required:

Default: Get user ID and auth token from X-User-Id and X-Auth-Token headers

  1. func main() {
  2. router := gin.Default()
  3. api := router.Group("/api")
  4. {
  5. api.GET("/books", gah.AuthRequiredMiddleware, func(c *gin.Context) {
  6. userID := c.MustGet("userID")
  7. c.JSON(200, gin.H{
  8. "userId": userID,
  9. })
  10. })
  11. }
  12. router.Run(":4000")
  13. }

Production Release Mode

  1. [GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
  2. - using env: export GIN_MODE=release
  3. - using code: gin.SetMode(gin.ReleaseMode)