Search code examples
gogo-xorm

xorm example not working: "runtime error: invalid memory address or nil pointer dereference"


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

Solution

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