gin啟動
昨天學習到gin如何返回一個json數(shù)據(jù)之后蝗羊,希望按照往常的開發(fā)經(jīng)驗添寺,定義統(tǒng)一的返回報文體褪猛,于是定義了以下結構
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)
}
自己研究源碼搗鼓半天也沒弄出來個所以然赌结,于是查閱資料才知道犯了一個很基礎的錯誤吭露。c.JSON方法底層使用了json.Marshal來序列化參數(shù)吠撮,這個方法只能序列化公有屬性,也就是說要把BaseResponse中字段的首字母大寫讲竿。首字母大寫表示公有可導出的泥兰,小寫是私有,這個知識點在GO中是比較基礎的题禀,很多地方都會用到鞋诗,需要牢記。
gin結合gorm
接下來就開始使用gorm來進行crud操作了迈嘹。我在service.go文件中提供了數(shù)據(jù)庫連接的配置與初始化方法削彬,在server.go文件中首先初始化數(shù)據(jù)庫連接,再啟動web容器接收請求秀仲。
- 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)
}
簡單地做了一個邏輯處理融痛,發(fā)送post請求localhost:2046/author?AuthorName=xxx,然后在數(shù)據(jù)庫中新增一條author記錄神僵,返回結果成功雁刷。
{
"Code": "000000",
"Message": "Create author with name : xxx"
}