[octopus-go] 初步完成gin gorm框架集成

This commit is contained in:
zeaslity
2023-03-07 17:32:35 +08:00
parent a18f2353a9
commit da56f6586c
9 changed files with 416 additions and 1 deletions

View File

@@ -0,0 +1,27 @@
package service
import (
"agent-go/entity"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func InitDB() *gorm.DB {
// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
dsn := "wmm:Superwmm.23@tcp(42.192.52.227:21306)/gormdb?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic(err)
}
// init the table
db.AutoMigrate(&entity.ServerInfo{})
// cache this db to global
entity.CONGIG.DB = db
return db
}

View File

@@ -0,0 +1,47 @@
package service
import (
"agent-go/entity"
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
type ServerAPI struct {
}
var ServerAPIService = new(ServerAPI)
func (s *ServerAPI) QueryAPI(c *gin.Context) {
fmt.Println("ServerAPI -> QueryAPI")
}
func (s *ServerAPI) CreateAPI(c *gin.Context) {
var serverInfo entity.ServerInfo
// get the body
err := c.ShouldBindJSON(&serverInfo)
if err != nil {
fmt.Println("server info error! pls check !")
}
fmt.Sprintf("server info is => %s", serverInfo)
db := entity.CONGIG.DB
create := db.Create(&serverInfo)
//user.ID // 返回插入数据的主键
//result.Error // 返回 error
//result.RowsAffected // 返回插入记录的条数
fmt.Sprintf(
"inter id is %s , resul error is %s, RowsAffected is %d ", serverInfo.ID, create.Error, create.RowsAffected)
}
func (s *ServerAPI) FakeAPI(c *gin.Context) {
c.JSON(
http.StatusOK,
new(entity.ServerInfo))
}