从golang-gin-realworld-example-app项目学写httpapi (四)
https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/routers.go
路由定义
package users
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"github.com/wangzitian0/golang-gin-starter-kit/common"
)
// 路由函数 用于用户注册、登录请求,注意 参数 *gin.RouterGroup, 用gin的groups router调用
func UsersRegister(router *gin.RouterGroup) {
router.POST("/", UsersRegistration)
router.POST("/login", UsersLogin)
}
// 路由函数 用于用户信息获取、更新请求
func UserRegister(router *gin.RouterGroup) {
router.GET("/", UserRetrieve)
router.PUT("/", UserUpdate)
}
// 路由函数 用于用户简介获取、增加关注、删除关注
// 请求参数变量,使用 :变量名
func ProfileRegister(router *gin.RouterGroup) {
router.GET("/:username", ProfileRetrieve)
router.POST("/:username/follow", ProfileFollow)
router.DELETE("/:username/follow", ProfileUnfollow)
}
// 请求处理函数,用户简介获取,注意 参数 *gin.Context
func ProfileRetrieve(c *gin.Context) {
// 获取请求参数 username
username := c.Param("username")
// 调用模型定义的FindOneUser函数
userModel, err := FindOneUser(&UserModel{Username: username})
if err != nil {
c.JSON(http.StatusNotFound, common.NewError("profile", errors.New("Invalid username")))
return
}
// 序列化查询的结果
profileSerializer := ProfileSerializer{c, userModel}
c.JSON(http.StatusOK, gin.H{"profile": profileSerializer.Response()})
}
// 请求处理函数,用户简介选择关注
func ProfileFollow(c *gin.Context) {
username := c.Param("username")
userModel, err := FindOneUser(&UserModel{Username: username})
if err != nil {
c.JSON(http.StatusNotFound, common.NewError("profile", errors.New("Invalid username")))
return
}
// 中间件
myUserModel := c.MustGet("my_user_model").(UserModel)
err = myUserModel.following(userModel)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("database", err))
return
}
serializer := ProfileSerializer{c, userModel}
c.JSON(http.StatusOK, gin.H{"profile": serializer.Response()})
}
// 请求处理函数,用户简介取消关注
func ProfileUnfollow(c *gin.Context) {
username := c.Param("username")
userModel, err := FindOneUser(&UserModel{Username: username})
if err != nil {
c.JSON(http.StatusNotFound, common.NewError("profile", errors.New("Invalid username")))
return
}
// 中间件
myUserModel := c.MustGet("my_user_model").(UserModel)
err = myUserModel.unFollowing(userModel)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("database", err))
return
}
serializer := ProfileSerializer{c, userModel}
c.JSON(http.StatusOK, gin.H{"profile": serializer.Response()})
}
// 请求处理函数,用户注册
func UsersRegistration(c *gin.Context) {
// 初始化注册验证
userModelValidator := NewUserModelValidator()
if err := userModelValidator.Bind(c); err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
return
}
if err := SaveOne(&userModelValidator.userModel); err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("database", err))
return
}
// 设置全局中间件 my_user_model
c.Set("my_user_model", userModelValidator.userModel)
serializer := UserSerializer{c}
c.JSON(http.StatusCreated, gin.H{"user": serializer.Response()})
}
// 请求处理函数,用户登录
func UsersLogin(c *gin.Context) {
// 初始化登录验证
loginValidator := NewLoginValidator()
if err := loginValidator.Bind(c); err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
return
}
// 验证用户是否存在
userModel, err := FindOneUser(&UserModel{Email: loginValidator.userModel.Email})
if err != nil {
c.JSON(http.StatusForbidden, common.NewError("login", errors.New("Not Registered email or invalid password")))
return
}
// 验证密码是否有效
if userModel.checkPassword(loginValidator.User.Password) != nil {
c.JSON(http.StatusForbidden, common.NewError("login", errors.New("Not Registered email or invalid password")))
return
}
// 更新上下文中的用户id
UpdateContextUserModel(c, userModel.ID)
serializer := UserSerializer{c}
c.JSON(http.StatusOK, gin.H{"user": serializer.Response()})
}
// 请求处理函数,用户信息获取
func UserRetrieve(c *gin.Context) {
// UserSerializer执行中间件
serializer := UserSerializer{c}
c.JSON(http.StatusOK, gin.H{"user": serializer.Response()})
}
// 请求处理函数,用户信息更新
func UserUpdate(c *gin.Context) {
myUserModel := c.MustGet("my_user_model").(UserModel)
userModelValidator := NewUserModelValidatorFillWith(myUserModel)
if err := userModelValidator.Bind(c); err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err))
return
}
userModelValidator.userModel.ID = myUserModel.ID
if err := myUserModel.Update(userModelValidator.userModel); err != nil {
c.JSON(http.StatusUnprocessableEntity, common.NewError("database", err))
return
}
// 更新上下文中的用户id
UpdateContextUserModel(c, myUserModel.ID)
serializer := UserSerializer{c}
c.JSON(http.StatusOK, gin.H{"user": serializer.Response()})
}
从golang-gin-realworld-example-app项目学写httpapi (四)的更多相关文章
- 从golang-gin-realworld-example-app项目学写httpapi (八)
https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/common/unit_test.go 单元测试 ...
- 从golang-gin-realworld-example-app项目学写httpapi (七)
https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/hello.go main调用 package ...
- 从golang-gin-realworld-example-app项目学写httpapi (六)
https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/validators.go 验证器 ...
- 从golang-gin-realworld-example-app项目学写httpapi (五)
https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/middlewares.go 中间件 ...
- 从golang-gin-realworld-example-app项目学写httpapi (三)
https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/serializers.go 序列化 ...
- 从golang-gin-realworld-example-app项目学写httpapi (二)
https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/models.go 模型定义 use ...
- 从golang-gin-realworld-example-app项目学写httpapi (一)
https://wangzitian0.github.io/2013/06/29/zero-to-one-1/ https://github.com/gothinkster/golang-gin-re ...
- Golang Gin 项目包依赖管理 godep 使用
Golang Gin 项目包依赖管理 godep 使用 标签(空格分隔): Go 在按照github.com/tools/godep文档go get完包以后,调整项目结构为$GOPATH/src/$P ...
- Golang Gin 项目使用 Swagger
Golang Gin 项目使用 Swagger 标签(空格分隔): Go 首先需要github.com/swaggo/gin-swagger和github.com/swaggo/gin-swagger ...
随机推荐
- 关于delete和对象复制
本码农的惯例,开篇废话几句... 前天小生又被虐了... 没办法,作为一个资深code user,我用代码的能力,解决问题的能力自问是不弱的... 但是自身的前端基础说实话还是不过硬,最明显的表现就是 ...
- windows 7 做AP
启动脚本: @echo off netsh wlan set hostednetwork mode=allow ssid=<ap-name> key=<password> ne ...
- Hibernate 4.3 SessionFactory
Configuration configuration = new Configuration().configure(); //以下这两句就是4.3的新用法 StandardServiceRegis ...
- CSS3 Media Queries_media queries, css3属性详解
Media Queries直译过来就是"媒体查询",在我们平时的Web页面中head部分常看到这样的一段代码: <link href="css/reset.css& ...
- [转]Upgrading to Async with Entity Framework, MVC, OData AsyncEntitySetController, Kendo UI, Glimpse & Generic Unit of Work Repository Framework v2.0
本文转自:http://www.tuicool.com/articles/BBVr6z Thanks to everyone for allowing us to give back to the . ...
- JAVA字符编码测试
几点注意: 1,ASCII码和ISO-8859-1都是单字节编码,ASCII码能表示128个字符,ISO-8859-1总共能表示256个字符.都不能表示中文,如果中文字符或其它不在IOS-8859码值 ...
- guava文档API制作成chm文件
将HTML制作成CHM.EXE需要用到一个小工具“HUGECHM”,将HTML打包成CHM文件 1.下载guava的最新的版本,网址:https://github.com/google/guava/w ...
- FE面试题库
一.HTML 序号 面试题目 难度等级 回答要点 H1 简述编写HTML需要注意哪些事项? ☆ DOCTYPE.charset.viewport.语义化.CSS与JS的位置.DOM层级.结构样式行为的 ...
- [javaSE] 网络编程(浏览器客户端-自定义服务端)
获取ServerSocket对象,new出来构造参数:int类型端口号 调用ServerSocket对象的accept()方法,得到Socket对象 获取PrintWriter对象,new出来,构造参 ...
- Spring Boot 打包jar部署服务器
部署方式:打包成jar部署 部署方式有两种,一种是传统的war包,另一种是打包成jar,推荐第二种方式部署 部署准备 1. jar包内置tomcat,无需服务器安装tomcat环境 2.需要JDK,且 ...