douzhantanju1849 2019-06-05 06:26
浏览 136

Golang Gin获取数据状态200正常,但未发送数据

Gin Get 200 OK status, but no data get on the page.

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

when I try to comment assets, err := au.GetAllAssets() in routers, it can post hello data and /api/v1/ping works fine.

Routers

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",
    })
}

Service

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)
}

model

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"`
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 数学建模,尽量用matlab回答,论文格式
    • ¥15 昨天挂载了一下u盘,然后拔了
    • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
    • ¥20 易康econgnition精度验证
    • ¥15 msix packaging tool打包问题
    • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
    • ¥15 python的qt5界面
    • ¥15 无线电能传输系统MATLAB仿真问题
    • ¥50 如何用脚本实现输入法的热键设置
    • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能