前提说明
大家都知道,Go语言是云原生技术的主力语言,因此想要更好的学习并掌握云原生技术的前提是能熟练的使用Go语言,今天就带大家再次使用Go语言搭建一个简单的Restful风格的后端服务,其中包含CRUD功能,但是由于能更方便快速的开发完成,web层使用了Gin框架,dao层,即数据库访问层的代码就没有进行数据库的连接,直接操作内存做数据的增删改查,如有详细教程的需要请留言哈~
好滴,废话不多说,在学习这篇文章之前建议大家先了解下除了Go基本语法和设计规范以外,还有Restful的一些要点和Gin框架的基础,这里我就推荐下相关文章吧:
Gin框架:
《快速入门Gin框架搭建HTTP服务》
Restful要点:
《RESTful介绍和使用教程》
具体代码
安装Gin
代码语言:shell复制go get -u github.com/gin-gonic/gin
项目结构:
cmd/web/main.go
代码语言:go复制package main
import (
"go_restful/pkg/web"
)
func main() {
web.RouterGroup("7000")
}
pkg/model/user.go
代码语言:go复制package model
type User struct {
Id int64 `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
pkg/dao/user_dao.go
代码语言: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
代码语言: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
代码语言: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
代码语言: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)
}
最后大家自行测试吧~
我正在参与2023腾讯技术创作特训营第二期有奖征文,瓜分万元奖池和键盘手表