从golang-gin-realworld-example-app项目学写httpapi (四)

https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/routers.go

路由定义

package usersimport ("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) {// 获取请求参数 usernameusername := 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_modelc.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}// 更新上下文中的用户idUpdateContextUserModel(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.IDif err := myUserModel.Update(userModelValidator.userModel); err != nil {c.JSON(http.StatusUnprocessableEntity, common.NewError("database", err))return}// 更新上下文中的用户idUpdateContextUserModel(c, myUserModel.ID)serializer := UserSerializer{c}c.JSON(http.StatusOK, gin.H{"user": serializer.Response()})
}

posted on 2018-11-20 10:04 北京涛子 阅读(...) 评论(...) 编辑 收藏

转载于:https://www.cnblogs.com/liujitao79/p/9987253.html

从golang-gin-realworld-example-app项目学写httpapi (四)相关推荐

  1. App项目实战之路(四):UI篇

    原创文章,转载请注明:转载自Keegan小钢 并标明原文链接:http://keeganlee.me/post/practice/20160903 微信订阅号:keeganlee_me 写于2016- ...

  2. (转载)带着项目学PHP第四讲 - 添加自动收缩浮动的客服(QQ客服,在线MSN,旺旺),兼容IE,Firefox

    本文对ecshop二次开发来说是很基础但是却很有用的,方便以后的开发,尽量按照原文转发,为了描述更清楚,可能会稍微加点注释. 转载自:http://bbs.ecshop.com/viewthread. ...

  3. App项目实战之路(二):API篇

    原创文章,转载请注明:转载自Keegan小钢 并标明原文链接:http://keeganlee.me/post/practice/20160812 微信订阅号:keeganlee_me 写于2016- ...

  4. [golang gin框架] 27.Gin 商城项目-购物车

    1.先来看一个问题 购物车数据保持到哪里? 1.购物车数据保存在本地 (cookie或者 redis缓存中),下面统一保存到cookie中,保存到redis中和cookie中逻辑步骤其实都是一样的 2 ...

  5. [golang gin框架] 24.Gin 商城项目-redis讲解以及操作

    一.reids相关文章 Redis五种数据类型及其应用场景 REDIS中的缓存穿透,缓存击穿,缓存雪崩原因以及解决方案 redis实现用户签到,统计活跃用户,用户在线状态,用户留存率 [golang ...

  6. [golang gin框架] 29.Gin 商城项目-用户登录,注册操作

    一.用户登录,注册界面展示说明 先看登录,注册界面以及相关流程,再根据流程写代码,一般网站的登录,注册功能都会在一个页面进行操作,还有的是在几个页面进行操作,这里讲解在几个页面进行注册的操作,步骤如下 ...

  7. [golang gin框架] 16.Gin 商城项目-商品模块数据表ER图关系分析

    1.数据表ER图 2.数据表相关 (1).商品分类表相关 1).数据表 -- ---------------------------- -- Table structure for goods_cat ...

  8. Golang gin框架

    gin框架学习 一.Gin 介绍 二.Gin 环境搭建 三.golang 程序的热加载 安装fresh 库 四.Gin 框架中的路由 4.1 路由概述 4.2 简单的路由配置 4.3 动态路由 4.4 ...

  9. 盘点 Github 上的高仿 app 项目

    点击上方蓝色"方志朋",选择"设为星标" 回复"666"获取独家整理的学习资料! 作者:水哥:来源:GitHubClub 学技术的,多多少少 ...

最新文章

  1. js 打开窗口window.open
  2. Python使用matplotlib可视化华夫饼图(Waffle Chart) 、华夫饼图可以直观地显示完成度(百分比)或者部分占整体的比例、华夫饼图适合于同类型指标的比较(Waffle Chart)
  3. vue-cli 项目配置路径别名
  4. 第七届蓝桥杯决赛真题 - 凑平方数-全排列+dfs+set去重
  5. QTP的那些事--操作excel的函数
  6. mysql有table函数吗_mysql_alter_table函数流程的部分修改和注解
  7. Dev C++ 实现Hello World
  8. 典型的SPI控制器的结构
  9. 电能储存系统行业调研报告 - 市场现状分析与发展前景预测(2021-2027年)
  10. 【Leetcode_easy】1103. Distribute Candies to People
  11. postgres初始化数据库
  12. MATLAB机械动力分析,基于MATLAB的柔性机械臂动力学分析
  13. Python-精准提取行政区省市区
  14. Nat Methods | 德州大学西南医学中心王涛/王莉等开发空间转录组数据降噪的新方法...
  15. 进行最大公约数和最小公倍数的求解
  16. java基础知识--(常用类)String类
  17. 2020顶尖黑帽seo优化教程
  18. mysql禁用空密码登录_允许phpmyadmin 空密码登陆
  19. React入门小册(三)组件
  20. LaTeX量子电路作图工具Qcircuit

热门文章

  1. java web项目中的根路径踩坑
  2. 我的在win10下安装tensorflow的过程
  3. ExtJs2.0学习系列(11)--Ext.XTemplate
  4. ExtJs2.0学习系列(9)--Ext.TabPanel之第一式
  5. Ext Grid Json分页(asp.net)
  6. js 绘制泳道图_软件工程师,如何绘制业务架构图 — 4.流程图
  7. leetcode —— 面试题68 - II. 二叉树的最近公共祖先
  8. Java下MySQL易用处理工具(支持XML/JavaBean)
  9. 极大似然估计求解多项式分布参数
  10. Dirichlet Process和Hierarchical Dirichlet Process的理解(PPT)