一文搞懂 Go 搭建 Restful 接口
作者:Barry Yan
- 2022 年 10 月 07 日 北京
本文字数:3178 字
阅读完需:约 10 分钟
前提说明
大家都知道,Go 语言是云原生技术的主力语言,因此想要更好的学习并掌握云原生技术的前提是能熟练的使用 Go 语言,今天就带大家再次使用 Go 语言搭建一个简单的 Restful 风格的后端服务,其中包含 CRUD 功能,但是由于能更方便快速的开发完成,web 层使用了 Gin 框架,dao 层,即数据库访问层的代码就没有进行数据库的连接,直接操作内存做数据的增删改查,如有详细教程的需要请留言哈~
好滴,废话不多说,在学习这篇文章之前建议大家先了解下除了 Go 基本语法和设计规范以外,还有 Restful 的一些要点和 Gin 框架的基础,这里我就推荐下相关文章吧:
Gin 框架:
Restful 要点:
具体代码
安装 Gin
go get -u github.com/gin-gonic/gin
复制代码
项目结构:
cmd/web/main.go
package main
import (
"go_restful/pkg/web"
)
func main() {
web.RouterGroup("7000")
}
复制代码
pkg/model/user.go
package model
type User struct {
Id int64 `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
复制代码
pkg/dao/user_dao.go
package dao
import (
"context"
"go_restful/pkg/model"
"log"
)
var users []*model.User
func init() {
userList := make([]*model.User, 0)
userList = append(userList, &model.User{Id: 1, Name: "zs", Age: 23})
userList = append(userList, &model.User{Id: 2, Name: "ls", Age: 24})
userList = append(userList, &model.User{Id: 3, Name: "ww", Age: 25})
users = userList
}
type UserDAO interface {
CreateUser(ctx context.Context, user *model.User) (bool, error)
List(ctx context.Context) ([]*model.User, error)
GetUserById(ctx context.Context, id int64) (model.User, error)
DeleteUserById(ctx context.Context, id int64) (bool, error)
UpdateUserById(ctx context.Context, user model.User) (bool, error)
}
type UserDaoImpl struct {
UserDB []*model.User
}
func NewUserDaoImpl() *UserDaoImpl {
return &UserDaoImpl{users}
}
func (u UserDaoImpl) CreateUser(ctx context.Context, user *model.User) (bool, error) {
users = append(u.UserDB, user)
printUsers()
return true, nil
}
func (u UserDaoImpl) List(ctx context.Context) ([]*model.User, error) {
return u.UserDB, nil
}
func (u UserDaoImpl) GetUserById(ctx context.Context, id int64) (model.User, error) {
return *u.UserDB[id-1], nil
}
func (u UserDaoImpl) DeleteUserById(ctx context.Context, id int64) (bool, error) {
newList := make([]*model.User, 0)
for i := range u.UserDB {
if i+1 != int(id) {
newList = append(newList, u.UserDB[i])
}
}
users = newList
printUsers()
return true, nil
}
func (u UserDaoImpl) UpdateUserById(ctx context.Context, user model.User) (bool, error) {
newList := make([]*model.User, 0)
for i := range u.UserDB {
if i+1 == int(user.Id) {
newList = append(newList, &user)
} else {
newList = append(newList, u.UserDB[i])
}
}
users = newList
printUsers()
return true, nil
}
func printUsers() {
for i := range users {
log.Print(users[i])
}
}
复制代码
pkg/web/controller/user_controller.go
package controller
import (
"context"
"encoding/json"
"github.com/gin-gonic/gin"
"go_restful/pkg/model"
"go_restful/pkg/web/controller/impl"
"io/ioutil"
"log"
"strconv"
)
type UserController interface {
CreateUser(ctx context.Context, user model.User) (bool, error)
List(ctx context.Context) ([]*model.User, error)
GetUserById(ctx context.Context, id int64) (model.User, error)
DeleteUserById(ctx context.Context, id int64) (bool, error)
UpdateUserById(ctx context.Context, user model.User) (bool, error)
}
//CreateUser 添加User
func CreateUser(c *gin.Context) {
body := c.Request.Body
bytes, err := ioutil.ReadAll(body)
user := model.User{}
json.Unmarshal(bytes, &user)
impl.MyUserControllerImpl.CreateUser(c, &user)
if err != nil {
log.Println(err)
}
c.JSON(200, "success")
}
//List 查看全部
func List(c *gin.Context) {
list, err := impl.MyUserControllerImpl.List(c)
if err != nil {
log.Println(err)
}
c.JSON(200, list)
}
//GetUserById 根据ID查看
func GetUserById(c *gin.Context) {
id := c.Param("id")
intid, _ := strconv.Atoi(id)
user, err := impl.MyUserControllerImpl.GetUserById(c, int64(intid))
if err != nil {
log.Println(err)
}
c.JSON(200, user)
}
//DeleteUserById 根据ID删除
func DeleteUserById(c *gin.Context) {
id := c.Param("id")
intid, _ := strconv.Atoi(id)
res, err := impl.MyUserControllerImpl.DeleteUserById(c, int64(intid))
if err != nil {
log.Println(err)
}
c.JSON(200, res)
}
//UpdateUserById 根据Id修改
func UpdateUserById(c *gin.Context) {
body := c.Request.Body
bytes, err := ioutil.ReadAll(body)
user := model.User{}
json.Unmarshal(bytes, &user)
if err != nil {
log.Println(err)
}
res, err := impl.MyUserControllerImpl.UpdateUserById(c, user)
c.JSON(200, res)
}
复制代码
pkg/web/controller/impl/user_controller.go
package impl
import (
"context"
"go_restful/pkg/dao"
"go_restful/pkg/model"
)
type UserControllerImpl struct {
dao *dao.UserDaoImpl
}
var MyUserControllerImpl *UserControllerImpl
func NewUserControllerImpl() *UserControllerImpl {
return &UserControllerImpl{
dao: dao.NewUserDaoImpl(),
}
}
func init() {
MyUserControllerImpl=NewUserControllerImpl()
}
func (u UserControllerImpl) CreateUser(ctx context.Context, user *model.User) (bool, error) {
return u.dao.CreateUser(ctx, user)
}
func (u UserControllerImpl) List(ctx context.Context) ([]*model.User, error) {
return u.dao.List(ctx)
}
func (u UserControllerImpl) GetUserById(ctx context.Context, id int64) (model.User, error) {
return u.dao.GetUserById(ctx, id)
}
func (u UserControllerImpl) DeleteUserById(ctx context.Context, id int64) (bool, error) {
return u.dao.DeleteUserById(ctx, id)
}
func (u UserControllerImpl) UpdateUserById(ctx context.Context, user model.User) (bool, error) {
return u.dao.UpdateUserById(ctx, user)
}
复制代码
pkg/web/router.go
package web
import (
"github.com/gin-gonic/gin"
"go_restful/pkg/web/controller"
)
func RouterGroup(port string) {
r := gin.Default()
router := r.Group("/")
{
router.POST("/save", controller.CreateUser)
router.GET("/list", controller.List)
router.GET("/get/:id", controller.GetUserById)
router.PUT("/update}", controller.UpdateUserById)
router.DELETE("/delete/:id", controller.DeleteUserById)
}
r.Run("127.0.0.1:" + port)
}
复制代码
最后大家自行测试吧~
划线
评论
复制
发布于: 刚刚阅读数: 3
版权声明: 本文为 InfoQ 作者【Barry Yan】的原创文章。
原文链接:【http://xie.infoq.cn/article/cff979b1bf1cb525648e360ab】。文章转载请联系作者。
Barry Yan
关注
做兴趣使然的Hero 2021.01.14 加入
Just do it.
评论