使用Golang Gin框架遵循MVC模式构建API:获取授权信息并查询数据库
以下是一个可能的实现,仅供参考:
package main
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
func main() {
db, err := gorm.Open("mysql", "user:password@tcp(host:port)/database?charset=utf8mb4&parseTime=True&loc=Local")
if err != nil {
panic(err)
}
defer db.Close()
db.AutoMigrate(&Balance{})
r := gin.Default()
balanceModel := NewBalanceModel(db)
controller := NewController(balanceModel)
r.Use(func(c *gin.Context) {
auth := c.GetHeader("Authorization")
if auth != "" {
resp, err := http.Get("https://api.k.com/v2/p/")
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
defer resp.Body.Close()
// TODO: parse JSON and extract username
c.Set("username", username)
}
})
r.GET("/balance", func(c *gin.Context) {
username, ok := c.Get("username")
if !ok {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
balance, err := controller.GetBalance(username)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.JSON(http.StatusOK, balance)
})
r.Run(":8080")
}
package main
import "github.com/jinzhu/gorm"
type Balance struct {
ID uint `gorm:"primary_key"
User string `gorm:"unique_index"
Money uint
Record uint
RecordDate string
Bot uint
BotDate string
MRecord uint
MRecordDate string
MRecordPack uint
CreatedAt string
UpdatedAt string
DeletedAt *string `sql:"index"
}
type BalanceModel struct {
db *gorm.DB
}
func NewBalanceModel(db *gorm.DB) *BalanceModel {
return &BalanceModel{db: db}
}
func (m *BalanceModel) GetByUsername(username string) (*Balance, error) {
var balance Balance
if err := m.db.Where("user = ?", username).First(&balance).Error; err != nil {
return nil, err
}
return &balance, nil
}
package main
import "errors"
type Controller struct {
model *BalanceModel
}
func NewController(model *BalanceModel) *Controller {
return &Controller{model: model}
}
func (c *Controller) GetBalance(username interface{}) (*Balance, error) {
balance, err := c.model.GetByUsername(username.(string))
if err != nil {
return nil, err
}
if balance == nil {
return nil, errors.New("balance not found")
}
return balance, nil
}
注意:这里的代码仅仅是一个示例,实际生产环境中还需要考虑很多问题,如错误处理、安全性、性能优化等。
原文地址: https://www.cveoy.top/t/topic/m6mG 著作权归作者所有。请勿转载和采集!