gin啟動(dòng)
昨天學(xué)習(xí)到gin如何返回一個(gè)json數(shù)據(jù)之后,希望按照往常的開發(fā)經(jīng)驗(yàn),定義統(tǒng)一的返回報(bào)文體,于是定義了以下結(jié)構(gòu)
type BaseResponse struct {
code string
message string
}
然而使用下面的代碼返回的數(shù)據(jù)一直是{}
func main() {
r := gin.Default()
r.GET("/hello", hello)
r.Run() // listen and serve on 0.0.0.0:8080
}
func hello(c *gin.Context) {
res := &BaseResponse{
code: "000000",
message: "hello world",
}
c.JSON(200, res)
}
自己研究源碼搗鼓半天也沒弄出來個(gè)所以然,于是查閱資料才知道犯了一個(gè)很基礎(chǔ)的錯(cuò)誤。c.JSON方法底層使用了json.Marshal來序列化參數(shù),這個(gè)方法只能序列化公有屬性,也就是說要把BaseResponse中字段的首字母大寫。首字母大寫表示公有可導(dǎo)出的,小寫是私有,這個(gè)知識(shí)點(diǎn)在GO中是比較基礎(chǔ)的,很多地方都會(huì)用到,需要牢記。
gin結(jié)合gorm
接下來就開始使用gorm來進(jìn)行crud操作了。我在service.go文件中提供了數(shù)據(jù)庫連接的配置與初始化方法,在server.go文件中首先初始化數(shù)據(jù)庫連接,再啟動(dòng)web容器接收請(qǐng)求。
- server.go
type BaseResponse struct {
Code string
Message string
}
func main() {
ConfigDb("1", "2", "3", 4, "5")
InitDb()
defer Db.Close()
r := gin.Default()
r.POST("/author", addAuthor)
r.Run("localhost:2046")
}
func addAuthor(c *gin.Context) {
author := &Author{
AuthorName: c.Query("AuthorName"),
CreateTime: time.Now(),
}
NewAuthor(*author)
message := fmt.Sprintf("Create author with name : %s", author.AuthorName)
res := &BaseResponse{
Code: "000000",
Message: message,
}
c.JSON(200, res)
}
- service.go
type DBConfig struct {
user, pw, host string
port int
dbName string
}
var config *DBConfig
var Db *gorm.DB
func ConfigDb(user, pw, host string, port int, dbName string) {
config = &DBConfig{
user: user,
pw: pw,
host: host,
port: port,
dbName: dbName,
}
}
func InitDb() *gorm.DB {
if config == nil {
panic("Do configuration first!")
}
// connect to mysql
connStr := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", config.user, config.pw, config.host, config.port, config.dbName)
var err error
Db, err = gorm.Open("mysql", connStr)
if err != nil {
panic("Connect to database fail")
}
Db.SingularTable(true)
Db.LogMode(true)
return Db
}
// crud
func NewAuthor(author Author) {
Db.Create(&author)
}
簡單地做了一個(gè)邏輯處理,發(fā)送post請(qǐng)求localhost:2046/author?AuthorName=xxx,然后在數(shù)據(jù)庫中新增一條author記錄,返回結(jié)果成功。
{
"Code": "000000",
"Message": "Create author with name : xxx"
}