使用Golang Gin框架实现MVC API:获取用户余额
controller.go
package controller
import (
"encoding/json"
"io/ioutil"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/xxx/models"
)
func GetBalance(c *gin.Context) {
auth := c.GetHeader("Authorization")
authValue := strings.TrimPrefix(auth, "Bearer ")
resp, err := http.Get("https://api.k.com/v2/p/?authorization=" + authValue)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": "error",
})
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": "error",
})
return
}
var data map[string]interface{}
if err := json.Unmarshal(body, &data); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": "error",
})
return
}
username, ok := data["user"].(map[string]interface{})["username"].(string)
if !ok {
c.JSON(http.StatusInternalServerError, gin.H{
"message": "error",
})
return
}
balance := &models.Balance{}
if err := models.DB.Where("user = ?", username).First(balance).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": "error",
})
return
}
c.JSON(http.StatusOK, gin.H{
"user": balance.User,
"money": balance.Money,
"record": balance.Record,
"record_date": balance.RecordDate,
"bot": balance.Bot,
"bot_date": balance.BotDate,
"m_record": balance.MRecord,
"m_record_date": balance.MRecordDate,
"m_record_package": balance.MRecordPackage,
})
}
models.go
package models
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var DB *gorm.DB
func init() {
dsn := "root:password@tcp(127.0.0.1:3306)/database?charset=utf8mb4&parseTime=True&loc=Local"
var err error
DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
}
type Balance struct {
User string `gorm:"primaryKey"
Money int
Record int
RecordDate string
Bot int
BotDate string
MRecord int
MRecordDate string
MRecordPackage string
}
原文地址: https://www.cveoy.top/t/topic/m6sV 著作权归作者所有。请勿转载和采集!