一,演示项目的相关信息:
1,项目地址:
https://github.com/liuhongdi/digv02
2,功能:演示gin返回restful格式的数据,
包括异常时的404/500等情况
3,项目结构:如图:
二,sql代码说明
-
CREATE TABLE `article` (
-
`articleId` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
-
`type` tinyint unsigned NOT NULL DEFAULT '0' COMMENT '类型',
-
`subject` varchar(500) NOT NULL DEFAULT '' COMMENT '标题',
-
`addTime` datetime NOT NULL DEFAULT '2020-11-19 00:00:00' COMMENT '添加时间',
-
`isHot` tinyint unsigned NOT NULL DEFAULT '0' COMMENT '是否热榜,0:非热,1,热',
-
`url` varchar(500) NOT NULL DEFAULT '' COMMENT '链接地址',
-
`domain` varchar(100) NOT NULL DEFAULT '' COMMENT '域',
-
`userId` bigint unsigned NOT NULL DEFAULT '0' COMMENT '推荐用户',
-
`approvalStaffId` int unsigned NOT NULL DEFAULT '0' COMMENT '批准员工',
-
`digSum` int unsigned NOT NULL DEFAULT '0' COMMENT '被顶的次数',
-
`commentSum` int unsigned NOT NULL DEFAULT '0' COMMENT '被评论的次数',
-
`isPublish` tinyint NOT NULL DEFAULT '0' COMMENT '0,未发布,1,已发布',
-
PRIMARY KEY (`articleId`),
-
KEY `isPublish` (`isPublish`)
-
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='文章表'
插入6条演示数据:
-
INSERT INTO `article` (`articleId`, `type`, `subject`, `addTime`, `isHot`, `url`, `domain`, `userId`, `approvalStaffId`, `digSum`, `commentSum`, `isPublish`) VALUES
-
(1, 0, '【最近,南非发现一座大油田】石油和天然气两种重要资源是南非储量的最短板,“贫油”的帽子也一直扣在南非的头上摘不下来。可就在最近,在南非海域进行油气勘探已久的道达尔透露了其新的勘探成果:在距离南非南部海岸约175公里的奥特尼夸盆地的11B/12B地区,再次发现了重要的凝析气,可能蕴藏着大量天然气及原油。', '2020-11-19 00:00:00', 1, 'https://mp.weixin.qq.com/s/1btbmouH-2KuIHUMoucq2w', '', 1, 1, 0, 0, 1),
-
(2, 1, '让喵喵来开启周五的早晨吧!', '2020-11-19 00:00:00', 0, 'https://m.weibo.cn/status/4573112073720433?', 'm.weibo.cn', 0, 0, 0, 0, 1),
-
(3, 0, '汤姆·赫兰德、黛茜·雷德利、麦斯·米科尔森、尼克·乔纳斯主演的《混沌漫步》公开预告。影片由《明日边缘》导演道格·里曼执导,暂时定档明年1月22日上映。', '2020-11-19 00:00:00', 1, 'http://news.mtime.com/2020/11/19/1604795.html', 'news.mtime.com', 0, 0, 0, 0, 1),
-
(4, 1, '扫地机器人这个东西确实方便,大多数时候把房间扫的比较干净,但还有很多边边角角清扫不上,希望厂家能够在app上显示出机器人的路线图,明确告知哪些路段没有照顾到,要不然就再开发一个项目经理机器人,跟在扫地机器人屁股后面监督。//@大窑儿:可以弄个步数排行榜,让机器人们互相点赞,揣摩,攀比,内卷,无意义竞争。', '2020-11-19 00:00:00', 0, '', '', 0, 0, 0, 0, 1),
-
(5, 0, '【世卫组织建议医生不要使用瑞德西韦治疗新冠】世卫组织指导小组表示,证据显示,瑞德西韦对提高新冠肺炎患者的存活率没有显著影响。这项建议发表在上周五的《英国医学杂志》中。', '2020-11-19 00:00:00', 0, 'https://www.thepaper.cn/newsDetail_forward_10067542', 'thepaper.cn', 0, 0, 0, 0, 1),
-
(6, 0, '11月19日0—24时,31个省(自治区、直辖市)和新疆生产建设兵团报告新增确诊病例17例,均为境外输入病例(福建6例,上海4例,陕西3例,广东2例,北京1例,四川1例);无新增死亡病例;新增疑似病例1例,为本土病例(在天津)。', '2020-11-19 00:00:00', 0, 'http://m.news.cctv.com/2020/11/20/ARTIIR9o72TuDF80s6hY2IvD201120.shtml', 'm.news.cctv.com', 0, 0, 0, 0, 1);
三,go代码说明
1,global/result.go
-
package global
-
-
import (
-
"github.com/gin-gonic/gin"
-
"net/http"
-
)
-
-
type Result struct {
-
Ctx *gin.Context
-
}
-
-
//返回的结果:
-
type ResultCont struct {
-
Code int `json:"code"` //提示代码
-
Msg string `json:"msg"` //提示信息
-
Data interface{} `json:"data"` //数据
-
}
-
-
func NewResult(ctx *gin.Context) *Result {
-
return &Result{Ctx: ctx}
-
}
-
-
//成功
-
func (r *Result) Success(data interface{}) {
-
if (data == nil) {
-
data = gin.H{}
-
}
-
res := ResultCont{}
-
res.Code = 0
-
res.Msg = ""
-
res.Data = data
-
r.Ctx.JSON(http.StatusOK,res)
-
}
-
-
//出错
-
func (r *Result)Error(code int,msg string) {
-
res := ResultCont{}
-
res.Code = code
-
res.Msg = msg
-
res.Data = gin.H{}
-
r.Ctx.JSON(http.StatusOK,res)
-
}
2,controller/articleController.go
-
package controller
-
-
import (
-
"fmt"
-
"github.com/gin-gonic/gin"
-
"github.com/liuhongdi/digv02/dao"
-
"github.com/liuhongdi/digv02/global"
-
"github.com/liuhongdi/digv02/model"
-
"github.com/liuhongdi/digv02/service"
-
"strconv"
-
)
-
-
type ArticleController struct{}
-
-
func NewArticleController() ArticleController {
-
return ArticleController{}
-
}
-
//得到一篇文章的详情
-
func (a *ArticleController) GetOne(c *gin.Context) {
-
result := global.NewResult(c)
-
id := c.Params.ByName("id")
-
fmt.Println("id:"+id);
-
-
articleId,err := strconv.ParseInt(id, 10, 64);
-
if (err != nil) {
-
result.Error(400,"参数错误")
-
fmt.Println(err.Error())
-
return
-
}
-
-
if (articleId == 100) {
-
var z int = 0
-
var i int = 100 / z
-
fmt.Println("i:%i",i)
-
}
-
-
articleOne,err := service.GetOneArticle(articleId);
-
if err != nil {
-
result.Error(404,"数据查询错误")
-
} else {
-
result.Success(&articleOne);
-
}
-
return
-
}
-
-
//得到多篇文章,按分页返回
-
func (a *ArticleController) GetList(c *gin.Context) {
-
result := global.NewResult(c)
-
page := c.DefaultQuery("page", "1")
-
pageInt, err := strconv.Atoi(page)
-
if (err != nil) {
-
//c.AbortWithStatus(400)
-
result.Error(400,"参数错误")
-
fmt.Println(err.Error())
-
return
-
}
-
pageSize := 2;
-
pageOffset := (pageInt-1) * pageSize
-
-
articles,err := service.GetArticleList(pageOffset,pageSize)
-
if err != nil {
-
//c.AbortWithStatus(404)
-
result.Error(404,"数据查询错误");
-
fmt.Println(err.Error())
-
} else {
-
sum,_ := dao.SelectcountAll()
-
pageInfo,_ := model.GetPageInfo(pageInt,pageSize,sum)
-
result.Success(gin.H{"list":&articles,"pageinfo":pageInfo});
-
}
-
return
-
}
3,router/router.go
-
package router
-
-
import (
-
"github.com/gin-gonic/gin"
-
"github.com/liuhongdi/digv02/controller"
-
"github.com/liuhongdi/digv02/global"
-
"log"
-
"runtime/debug"
-
)
-
-
func Router() *gin.Engine {
-
router := gin.Default()
-
//处理异常
-
router.NoRoute(HandleNotFound)
-
router.NoMethod(HandleNotFound)
-
router.Use(Recover)
-
-
// 路径映射
-
articlec:=controller.NewArticleController()
-
router.GET("/article/getone/:id", articlec.GetOne);
-
router.GET("/article/list", articlec.GetList);
-
return router
-
}
-
-
//404
-
func HandleNotFound(c *gin.Context) {
-
global.NewResult(c).Error(404,"资源未找到")
-
return
-
}
-
-
//500
-
func Recover(c *gin.Context) {
-
defer func() {
-
if r := recover(); r != nil {
-
//打印错误堆栈信息
-
log.Printf("panic: %v ", r)
-
debug.PrintStack()
-
global.NewResult(c).Error(500,"服务器内部错误")
-
}
-
}()
-
//继续后续接口调用
-
c.Next()
-
}
4,其他代码可以访问github上查看
四,测试效果
1,正常的输出
访问:
http://127.0.0.1:8080/article/list?page=1
返回:
2,无效地址的访问:404
访问一个不存在的地址:如:
http://127.0.0.1:8080/abc
返回:
3,传递有问题的参数引发内部错误:500
例如:访问:
http://127.0.0.1:8080/article/getone/100
返回:
五,查看库的版本:
-
module github.com/liuhongdi/digv02
-
-
go 1.15
-
-
require (
-
github.com/gin-gonic/gin v1.6.3
-
github.com/jinzhu/gorm v1.9.16
-
)