美文网首页
Gin框架与《Web Development with Go》实

Gin框架与《Web Development with Go》实

作者: Cyberpunk_ZYM | 来源:发表于2017-06-09 18:28 被阅读0次

    Users资源的处理函数

    src/taskmanager2/routers2/user.go

    package routers2
    
    import (
        "gopkg.in/gin-gonic/gin.v1"
        "taskmanager2/controllers2"
    )
    
    func SetUserRoutes(router *gin.Engine) *gin.Engine {
    
        userR := router.Group("/tm2/users")
        {
            userR.POST("/register", controllers2.Register)
            userR.POST("/login", controllers2.Login)
        }
        return router
    }
    
    

    JSON资源模型

    src/taskmanager2/controllers2/resources.go

    package controllers2
    
    import (
        "taskmanager2/models2"
    )
    
    type (
        UserResource struct {
            Data models2.User `json:"data"`
        }
        LoginResource struct {
            Data LoginModel `json:"data"`
        }
        AuthUserResource struct {
            Data AuthUserModel `json:"data"`
        }
        TaskResource struct {
            Data models2.Task `json:"data"`
        }
        TasksResource struct {
            Data []models2.Task `json:"data"`
        }
        NoteResource struct {
            Data NoteModel `json:"data"`
        }
        LoginModel struct {
            Email    string `json:"email"`
            Password string `json:"password"`
        }
        AuthUserModel struct {
            User  models2.User `json:"user"`
            Token string      `json:"token"`
        }
        NoteModel struct {
            TaskId      string `json:"taskid"`
            Description string `json:"description"`
        }
    )
    

    Users资源的处理函数

    src/taskmanager2/controllers2/userCtrler.go
    对应路径“/tm2/users/register”

    package controllers2
    
    import (
        "net/http"
        "gopkg.in/gin-gonic/gin.v1"
        "taskmanager2/common2"
        "taskmanager2/data2"
        "taskmanager2/models2"
    )
    
    // Handler for HTTP Post - /tm2/users/register
    func Register(c *gin.Context) {
        var dataResource UserResource
    
        err := c.BindJSON(&dataResource)
        if err != nil {
            common2.DisplayAppError(
                c,
                err,
                "Invalid User data",
                500,
            )
            return
        }
    
        user := &dataResource.Data
        context := NewContext()
        defer context.Close()
        col := context.DbCollection("users")
        repo := &data2.UserRepository{C: col}
        repo.CreateUser(user)
        // Clean-up the hashpassword to eliminate it from response JSON
        user.HashPassword = nil
    
        c.JSON(http.StatusCreated, dataResource)
    }
    ...
    

    src/taskmanager2/controllers2/userCtrler.go
    对应路径“/tm2/users/login”

    ...
    // Handler for HTTP Post - /tm2/users/login
    func Login(c *gin.Context) {
        var dataResource LoginResource
        var token string
        // Decode the incoming Login json
        err := c.BindJSON(&dataResource)
        if err != nil {
            common2.DisplayAppError(
                c,
                err,
                "Invalid Login data",
                500,
            )
            return
        }
        loginModel := dataResource.Data
        loginUser := models2.User{
            Email:    loginModel.Email,
            Password: loginModel.Password,
        }
        context := NewContext()
        defer context.Close()
        col := context.DbCollection("users")
        repo := &data2.UserRepository{C: col}
        // Authenticate the login user
        user, err := repo.Login(loginUser)
        if err != nil {
            common2.DisplayAppError(
                c,
                err,
                "Invalid login credentials",
                401,
            )
            return
        }
        // Generate JWT token
        token, err = common2.GenerateJWT(user.Email, "member")
        if err != nil {
            common2.DisplayAppError(
                c,
                err,
                "Eror while generating the access token",
                500,
            )
            return
        }
    
        // Clean-up the hashpassword to eliminate it from response JSON
        user.HashPassword = nil
        authUser := AuthUserModel{
            User:  user,
            Token: token,
        }
    
        c.JSON(http.StatusOK, AuthUserResource{Data: authUser})
    }
    
    

    注册新用户

    使用mongodb:


    使用图形工具:


    src/taskmanager2/data2/userRepository.go

    package data2
    
    import (
        "golang.org/x/crypto/bcrypt"
        "gopkg.in/mgo.v2"
        "gopkg.in/mgo.v2/bson"
    
        "taskmanager2/models2"
    )
    
    type UserRepository struct {
        C *mgo.Collection
    }
    
    func (r *UserRepository) CreateUser(user *models2.User) error {
        obj_id := bson.NewObjectId()
        user.Id = obj_id
        hpass, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
        if err != nil {
            panic(err)
        }
        user.HashPassword = hpass
        //clear the incoming text password
        user.Password = ""
        err = r.C.Insert(&user)
        return err
    }
    
    func (r *UserRepository) Login(user models2.User) (u models2.User, err error) {
    
        err = r.C.Find(bson.M{"email": user.Email}).One(&u)
        if err != nil {
            return
        }
        // Validate password
        err = bcrypt.CompareHashAndPassword(u.HashPassword, []byte(user.Password))
        if err != nil {
            u = models2.User{}
        }
        return
    }
    
    

    使用postman进行注册:


    user-register.png

    其响应为:

    查看数据库:

    登录进系统

    在postman中进行新用户的登录:

    登录后的相应如下,其中有jwt值的返回:

    相关文章

      网友评论

          本文标题:Gin框架与《Web Development with Go》实

          本文链接:https://www.haomeiwen.com/subject/zisnfxtx.html