飞道的博客

go的web框架Iris和gorm搭建基础版本的增删改查

554人阅读  评论(0)

 

go语言 有很多优秀的web框架,于是乎,就自己动手 从零开始搭建一个demo,除了有些东西下载比较麻烦,其它的都很好弄,下面贴出我搭建的工程.在开始项目之前需要下载并安装好go的环境以及iris还有gorm的环境.

一:首先贴出我的项目结构图:

二:各分层情况代码

   controlle层


  
  1. package controllers
  2. import (
  3. "github.com/kataras/iris/context"
  4. "github.com/spf13/cast"
  5. "iris_demo/models"
  6. "iris_demo/service"
  7. "log"
  8. )
  9. type UserController struct {
  10. Service service.UserService
  11. }
  12. func NewUserController() *UserController {
  13. return &UserController{Service:service.NewUserService()}
  14. }
  15. //查询所有
  16. func (self *UserController) GetList()(result *models.Result) {
  17. return self.Service.GetUserList()
  18. }
  19. //保存 and 修改
  20. func (self *UserController) PostSaveUser(ctx context.Context)(result models.Result) {
  21. user := new(models.User)
  22. err := ctx.ReadForm(user)
  23. if err != nil{
  24. log.Println(err)
  25. result.Msg = "数据有错误"
  26. return
  27. }
  28. return self.Service.PostSaveUser(*user)
  29. }
  30. //根据id查询
  31. func (self *UserController) GetUserById(ctx context.Context)(result models.Result) {
  32. id := ctx.PostValue( "id")
  33. if id == "" {
  34. result.Code = 400
  35. result.Msg = "缺少参数id"
  36. return
  37. }
  38. return self.Service.GetUserById(cast.ToUint(id))
  39. }
  40. //根据id删除
  41. func (self *UserController) PostDelUser(ctx context.Context)(result models.Result) {
  42. id := ctx.PostValue( "id")
  43. if id == "" {
  44. result.Code = 400
  45. result.Msg = "缺少参数id"
  46. return
  47. }
  48. return self.Service.DelUser(cast.ToUint(id))
  49. }

service层


  
  1. package service
  2. import (
  3. "iris_demo/models"
  4. "iris_demo/repo"
  5. )
  6. type UserService interface {
  7. GetUserList () *models.Result
  8. PostSaveUser(user models.User) (result models.Result)
  9. GetUserById(id uint) (result models.Result)
  10. DelUser(id uint) (result models.Result)
  11. }
  12. type userService struct {}
  13. func NewUserService() UserService{
  14. return &userService{}
  15. }
  16. var userRepo = repo.NewUserRepository()
  17. func (self userService)GetUserList() *models.Result{
  18. books := userRepo.GetUserList()
  19. result := new (models.Result)
  20. result.Data = books
  21. result.Code = 200
  22. result.Msg = "SUCCESS"
  23. return result
  24. }
  25. func (self userService) PostSaveUser(user models.User)(result models.Result){
  26. err := userRepo.SaveUser(user)
  27. if err != nil{
  28. result.Code = 400
  29. result.Msg = err.Error()
  30. } else{
  31. result.Code = 200
  32. result.Msg = "SUCCESS"
  33. user := userRepo.GetUserByName(user.Name)
  34. result.Data = user
  35. }
  36. return
  37. }
  38. func (self userService) GetUserById(id uint)(result models.Result){
  39. user,err := userRepo.GetUserById(id)
  40. if err!= nil{
  41. result.Code = 400
  42. result.Msg = err.Error()
  43. } else{
  44. result.Data = user
  45. result.Code = 200
  46. result.Msg = "SUCCESS"
  47. }
  48. return result
  49. }
  50. func (self userService) DelUser(id uint)(result models.Result){
  51. err := userRepo.DeleteUser(id)
  52. if err!= nil{
  53. result.Code = 400
  54. result.Msg = err.Error()
  55. } else{
  56. result.Code = 200
  57. result.Msg = "SUCCESS"
  58. list := userRepo.GetUserList()
  59. result.Data = list
  60. }
  61. return
  62. }

Repository层


  
  1. package repo
  2. import (
  3. "iris_demo/datasource"
  4. "iris_demo/models"
  5. )
  6. type UserRepository interface {
  7. GetUserList() *[]models.User
  8. SaveUser(book models.User)(err error)
  9. GetUserById(id uint)(book models.User,err error)
  10. DeleteUser(id uint)(err error)
  11. GetUserByName(name string )*[]models.User
  12. }
  13. func NewUserRepository() UserRepository{
  14. return &userRepository{}
  15. }
  16. var db = datasource.GetDB()
  17. type userRepository struct {}
  18. func (self userRepository) GetUserList()*[]models.User{
  19. user:= new([]models.User)
  20. err:=db.Raw( `select * FROM user`).Scan(user).RowsAffected
  21. if err > 0 {
  22. return user
  23. } else{
  24. return nil
  25. }
  26. }
  27. func (self userRepository)GetUserByName(name string )*[]models.User{
  28. user:= new([]models.User)
  29. err:=db.Raw( `select * FROM user where user.name = ?`,name).Scan(user).RowsAffected
  30. if err > 0 {
  31. return user
  32. } else{
  33. return nil
  34. }
  35. }
  36. func (self userRepository) SaveUser(user models.User)(err error){
  37. if user.ID != 0{
  38. err := db.Save(&user).Error
  39. return err
  40. } else {
  41. err := db.Create(&user).Error
  42. return err
  43. }
  44. }
  45. func (self userRepository) GetUserById(id uint)(user models.User,err error){
  46. err = db.First(&user,id).Error
  47. return user,err
  48. }
  49. func (self userRepository) DeleteUser(id uint)(err error){
  50. user:= new(models.User)
  51. user.ID = id
  52. err = db.Unscoped().Delete(&user).Error
  53. return err
  54. }

 入口main 方法


  
  1. package main
  2. import (
  3. "flag"
  4. "github.com/kataras/iris"
  5. "iris_demo/conf"
  6. "iris_demo/route"
  7. )
  8. func main() {
  9. flag.Parse()
  10. app := newApp()
  11. route.InitRouter(app)
  12. err := app.Run(iris.Addr( ":"+conf.Sysconfig.Port), iris.WithoutServerError(iris.ErrServerClosed))
  13. if err != nil {
  14. panic(err)
  15. }
  16. }
  17. func newApp() *iris.Application {
  18. app := iris.New()
  19. app.Configure(iris.WithOptimizations)
  20. app.AllowMethods(iris.MethodOptions)
  21. return app
  22. }

model

  user


  
  1. package models
  2. type User struct {
  3. ID uint `gorm:"primary_key"`
  4. Name string `gorm:"type:varchar(20);not null;"`
  5. Age string `gorm:"type:varchar(10);not null;"`
  6. Sex string `gorm:"type:varchar(20);not null;"`
  7. }

 Result


  
  1. package models
  2. type Result struct {
  3. Code int
  4. Msg string
  5. Data interface{}
  6. }
  7. func NewResult(data interface{}, c int, m ...string) *Result {
  8. r := &Result{Data: data, Code: c}
  9. if e, ok := data.(error); ok {
  10. if m == nil {
  11. r.Msg = e.Error()
  12. }
  13. } else {
  14. r.Msg = "SUCCESS"
  15. }
  16. if len(m) > 0 {
  17. r.Msg = m[ 0]
  18. }
  19. return r
  20. }

初始化表


  
  1. package datasource
  2. import (
  3. "iris_demo/models"
  4. )
  5. // 初始化表 如果不存在该表 则自动创建
  6. func Createtable() {
  7. GetDB().AutoMigrate(
  8. &models.User{},
  9. )
  10. }

数据库连接


  
  1. package datasource
  2. import (
  3. _ "github.com/go-sql-driver/mysql"
  4. "github.com/jinzhu/gorm"
  5. "iris_demo/conf"
  6. "strings"
  7. "time"
  8. )
  9. var db *gorm.DB
  10. func GetDB() *gorm.DB {
  11. return db
  12. }
  13. func init() {
  14. path := strings.Join([] string{conf.Sysconfig.DBUserName, ":", conf.Sysconfig.DBPassword, "@(", conf.Sysconfig.DBIp, ":", conf.Sysconfig.DBPort, ")/", conf.Sysconfig.DBName, "?charset=utf8&parseTime=true"}, "")
  15. var err error
  16. db, err = gorm.Open( "mysql", path)
  17. if err != nil{
  18. panic(err)
  19. }
  20. db.SingularTable( true)
  21. db.DB().SetConnMaxLifetime( 1 * time.Second)
  22. db.DB().SetMaxIdleConns( 20) //最大打开的连接数
  23. db.DB().SetMaxOpenConns( 2000) //设置最大闲置个数
  24. db.SingularTable( true) //表生成结尾不带s
  25. // 启用Logger,显示详细日志
  26. db.LogMode( true)
  27. Createtable();
  28. }

 

 

路由设置


  
  1. package route
  2. import (
  3. "github.com/kataras/iris"
  4. "github.com/kataras/iris/mvc"
  5. "iris_demo/controllers"
  6. )
  7. func InitRouter(app *iris.Application) {
  8. bathUrl := "/api"
  9. mvc.New(app.Party(bathUrl + "/user")).Handle(controllers.NewUserController())
  10. }

 

 数据库参数设置 config.json


  
  1. {
  2. "Port": "端口",
  3. "DBUserName": "root",
  4. "DBPassword": "数据库密码",
  5. "DBIp": "数据库地址",
  6. "DBPort": "3306",
  7. "DBName": "数据库Name"
  8. }

配置config


  
  1. package conf
  2. import (
  3. "github.com/json-iterator/go"
  4. "io/ioutil"
  5. )
  6. var Sysconfig = &sysconfig{}
  7. func init() {
  8. //指定对应的json配置文件
  9. b, err := ioutil.ReadFile( "config.json")
  10. if err != nil {
  11. panic( "Sys config read err")
  12. }
  13. err = jsoniter.Unmarshal(b, Sysconfig)
  14. if err != nil {
  15. panic(err)
  16. }
  17. }
  18. type sysconfig struct {
  19. Port string `json:"Port"`
  20. DBUserName string `json:"DBUserName"`
  21. DBPassword string `json:"DBPassword"`
  22. DBIp string `json:"DBIp"`
  23. DBPort string `json:"DBPort"`
  24. DBName string `json:"DBName"`
  25. }

启动项目,第一次启动会自动给我们创建表,我们可以通过控制台看到日志

三:测试

   添加数据

    

在查看数据库,可以看到数据插入成功

  修改数据

数据库

根据ID查询

查询所有(为了看到效果 我在插入一条)

 

根据ID删除数据(删除之后 我们在查询所有 会发现我们那条数据已经被删除掉了)

查看数据库发现只有一条了

 

到此,简单的增删改查已经全部完成.


转载:https://blog.csdn.net/FindHuni/article/details/105709378
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场