Gin获得200 OK状态,但是页面上没有数据。
click me to see the error page
$ go run main.go
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)
[GIN-debug] GET /api/v1/ping --> goGin/app/routers/api/v1.Hello (3 handlers)
[GIN-debug] GET /api/v1/assets --> goGin/app/routers/api/v1.GetAssets (3 handlers)
2019/06/05 16:05:06 [info] start http server listening :8880
[GIN] 2019/06/05 - 16:05:13 | 200 | 437.8697ms | ::1 | GET /api/v1/assets
[GIN] 2019/06/05 - 16:05:13 | 200 | 551.5161ms | ::1 | GET /api/v1/assets
[GIN] 2019/06/05 - 16:05:19 | 200 | 202.4586ms | ::1 | GET /api/v1/assets
当我尝试在路由器中评论assets, err := au.GetAllAssets()
时,它可以发布问候数据,并且/ api / v1 / ping可以正常工作。
路由器
package routers
import (
"github.com/gin-gonic/gin"
_ "go-gin-example/docs"
"goGin/app/routers/api/v1"
)
// InitRouter initialize routing information
func InitRouter() *gin.Engine {
r := gin.Default()
apiv1 := r.Group("/api/v1")
//apiv1.Use(jwt.JWT())
{
apiv1.GET("/ping", v1.Hello)
apiv1.GET("/assets", v1.GetAssets)
}
return r
}
package v1
import (
"net/http"
"fmt"
"github.com/gin-gonic/gin"
"goGin/app/service/asset_service"
)
func GetAssets(c *gin.Context) {
au:= asset_service.NewAssetService()
assets, err := au.GetAllAssets()
if err != nil {
c.AbortWithStatus(404)
fmt.Println(err)
} else {
c.JSON(http.StatusOK, gin.H {
"status": http.StatusOK,
"data": assets[0],
})
}
}
func Hello(c *gin.Context) {
c.JSON(http.StatusOK, gin.H {
"status": http.StatusOK,
"message": "pong",
})
}
服务
package asset_service
import (
"goGin/app/model"
"goGin/app/dao/mysqlRepo"
)
type Service interface {
GetAllAssets() (asset []models.Asset, err error)
//GetById(id string) (asset *models.Asset)
//InsertOneAsset(asset *models.Asset) (ass *models.Asset)
}
type assetService struct {
assetRepo mysqlRepo.Repository
}
func NewAssetService() Service {
ar := mysqlRepo.NewMysqlAssetRepository()
return &assetService{assetRepo: ar}
}
func (ar *assetService) GetAllAssets() ([]models.Asset, error) {
assets, err := ar.assetRepo.GetAllAssets()
return assets, err
}
dao
package mysqlRepo
import (
"fmt"
"time"
"goGin/app/model"
"github.com/jinzhu/gorm"
)
type Repository interface {
GetAllAssets() (assets []models.Asset, err error)
//GetById(id string) (asset *models.Asset)
//InsertOneAsset(asset *models.Asset) (ass *models.Asset)
}
type MysqlAssetRepository struct {
conn *gorm.DB
}
// Connect to MySQL
func NewMysqlAssetRepository() Repository {
return &MysqlAssetRepository{db}
}
// GetAllAssets function gets all assets
func (m *MysqlAssetRepository) GetAllAssets() ([]models.Asset, error) {
var assets []models.Asset
query := `SELECT * FROM assets ORDER BY assets.OrganisationID, assets.Name ASC`
rows, err := m.conn.Raw(query).Rows()
defer rows.Close()
models.CheckErr(err)
if err != nil {
return nil, err
}
for rows.Next() {
var asset models.Asset
// ScanRows scan a row into user
db.ScanRows(rows, &asset)
assets = append(assets,asset)
}
return assets, nil
}
func genAssetGUID() string {
id := Uniqid("AST_")
return id
}
func Uniqid(prefix string) string {
now := time.Now()
sec := now.Unix()
usec := now.UnixNano() % 0x100000
return fmt.Sprintf("%s%08x%05x", prefix, sec, usec)
}
模型
package mysqlRepo
import (
"log"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"goGin/library/setting"
)
var (
db *gorm.DB
err error
)
func Setup() {
dbAddress := setting.DatabaseSetting.Host
dbUser := setting.DatabaseSetting.User
dbPwd := setting.DatabaseSetting.Password
dbName := setting.DatabaseSetting.Name
dbString := dbUser + ":" + dbPwd + "@tcp(" + dbAddress + ")/" + dbName + "?charset=utf8"
db, err = gorm.Open(setting.DatabaseSetting.Type, dbString)
if err != nil {
log.Fatalf("models.Setup err: %v", err)
}
db.DB().SetMaxIdleConns(10)
db.DB().SetMaxOpenConns(100)
}
package models
type Asset struct {
ID string `gorm:"column:ID;primary_key" json:"ID"`
IMEI string `gorm:"column:IMEI;null" json:"IMEI"`
Name string `gorm:"column:Name;null" json:"Name"`
Contact string `gorm:"column:Contact;" json:"Contact"`
Email string `gorm:"column:Email;" json:"Email"`
Latitude float64 `gorm:"column:Latitude;null" json:"Latitude"`
Longitude float64 `gorm:"column:Longitude;null" json:"Longitude"`
HorizontalAccuracy float64 `gorm:"column:HorizontalAccuracy;null" json:"HorizontalAccuracy"`
Speed float64 `gorm:"column:Speed;null" json:"Speed"`
Heading float64 `gorm:"column:Heading;null" json:"Heading"`
Deployed int `gorm:"column:Deployed;null" json:"Deployed"`
BatteryLife string `gorm:"column:BatteryLife;null" json:"BatteryLife"`
Status string `gorm:"column:Status;null" json:"Status"`
OrganisationID string `gorm:"column:OrganisationID;null" json:"OrganisationID"`
CreatedDate string `gorm:"column:CreatedDate;null" json:"CreatedDate"`
LastModified string `gorm:"column:LastModified;null" json:"LastModified"`
TemplateID string `gorm:"column:TemplateID;null" json:"TemplateID"`
OffTimer int `gorm:"column:OffTimer;null" json:"OffTimer"`
SafetyTimer int `gorm:"column:SafetyTimer;null" json:"SafetyTimer"`
HazardTimer int `gorm:"column:HazardTimer;null" json:"HazardTimer"`
OffTimerTemp int `gorm:"column:OffTimerTemp;null" json:"OffTimerTemp"`
LastSignedOn string `gorm:"column:LastSignedOn;null" json:"LastSignedOn"`
LastCheckIn string `gorm:"column:LastCheckIn;null" json:"LastCheckIn"`
HazardTimerStartedTime string `gorm:"column:HazardTimerStartedTime;null" json:"HazardTimerStartedTime"`
ActiveDeviceType string `gorm:"column:ActiveDeviceType;null" json:"ActiveDeviceType"`
CurrentDeviceID string `gorm:"column:CurrentDeviceID;null" json:"CurrentDeviceID"`
LastEventTimeStamp string `gorm:"column:LastEventTimeStamp;null" json:"LastEventTimeStamp"`
LoginPassword string `gorm:"column:LoginPassword;null" json:"LoginPassword"`
TrackingInterval int `gorm:"column:TrackingInterval;null" json:"TrackingInterval"`
NewEvent int `gorm:"column:NewEvent;null" json:"NewEvent"`
Display int `gorm:"column:Display;null" json:"Display"`
TakeControl int `gorm:"column:TakeControl;null" json:"TakeControl"`
AssetStatus string `gorm:"column:AssetStatus;null" json:"AssetStatus"`
NewMessage int `gorm:"column:NewMessage;null" json:"NewMessage"`
ResetPassword string `gorm:"column:ResetPassword;null" json:"ResetPassword"`
}