duan_88598 2019-05-31 13:50
浏览 76
已采纳

xorm示例不起作用:“运行时错误:无效的内存地址或nil指针取消引用”

Based on this example i tried to write a program that would return some data from a database. Unfortunately, (more-or-less) the same program structure causes memory errors here err := orm.Find(&sensorDataEntry) according to runtime console output.

What am i missing here? Both example and my program has the slice created using make() and uses reference in Find() method.

Code in question:

package main

import (
    "fmt"
    "net/http"
    "time"

    "github.com/gorilla/mux"
    _ "github.com/lib/pq"
    //"database/sql"
    "github.com/go-xorm/xorm"

)

var orm *xorm.Engine

func newRouter() *mux.Router {
    r := mux.NewRouter()
    r.HandleFunc("/sensorentries", GetSensorEntriesHandler).Methods("GET")

    return r
}

type SensorDataEntry struct {
    id int `xorm:"int"`
    sensor_id string `xorm:"varchar(32)"`
    key string `xorm:"varchar(128)"`
    value float64 `xorm:"numeric(20,2)"`
    created_at time.Time `xorm:"timestamp"`
}

func main() {
    connString := "host=server.lan user=x password=x dbname=testdb sslmode=disable"
    orm, err := xorm.NewEngine("postgres", connString)
    //orm.ShowSQL(true)

    if err != nil {
        println(err)
        return
    }

    if err = orm.Sync2(SensorDataEntry{}); err != nil {
        return
    }

    r := newRouter()
    http.ListenAndServe(":8080", r)
}

func GetSensorEntriesHandler(resp http.ResponseWriter, req *http.Request) {
    sensorDataEntry := make([]SensorDataEntry, 0)
    err := orm.Find(&sensorDataEntry)

    if err != nil {
        println(err)
    }

    fmt.Println(sensorDataEntry)

    fmt.Fprintf(resp, "return text")
}
  • 写回答

1条回答 默认 最新

  • drvpvmz16241016 2019-05-31 14:51
    关注

    As noted by mkopriva, the problem was using the same variable name for assignment.

    Solution for the problem was:

    instead of

    orm, err := xorm.NewEngine("postgres", connString)
    

    use

    var err error
    orm, err = xorm.NewEngine("postgres", connString)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效