0

I'm new in golang i want to use it to make a rest API. I'm blocking on this problem. I don't understand it because the function CreateEffect runs good.

My problem is in the function "getEffects" at line: "db.Find(&effects)"

This is my code:

var db *gorm.DB
var err error

func getEffects (w http.ResponseWriter, r *http.Request) {
    var effects []Effects
    db.Find(&effects)
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(&effects)
}

func main () {
    db, err := gorm.Open("sqlite3", "gorm.db")
    defer db.Close()

    //Initialisation des routes
    r:= mux.NewRouter()
    r.HandleFunc("/effects", getEffects).Methods("GET")

    //Start serveur port 5080
    log.Fatal(http.ListenAndServe(":5080",r))
}

This is the runtime error:

2019/09/28 22:46:54 http: panic serving 127.0.0.1:36488: runtime error: invalid memory address or nil pointer dereference
goroutine 27 [running]:

The full code is here: https://pastebin.com/sbzhK8YV

Thanks for help

  • 3
    `:=` *re*-declares the identifiers on the left hand side in its containing scope. Therefore, in the outer scope, `db` is left `nil`. You can predeclare `err` in `main` and then use `=` instead. For example: `var err error` and then `db, err = gorm.Open(...`. Now the package level `db` will not be `nil` when referenced in `getEffects`. – mkopriva Sep 28 '19 at 21:13

1 Answers1

1

When you write db, err := gorm.Open("sqlite3", "gorm.db"), you are essentially declaring a "new" local variable, which shadows the global "db".

Hence the "db" variable being used in db.Find(&effects) was never actually initialized.

To give you some more context, in case you are starting with Go. This runtime error is logically similar to C's segmentation fault, or Java's null pointer exception. If you are using an IDE, make sure to configure it in a way, that it shows such declarations as warnings(or even error). Re-declaring a variable with same name is almost never a good idea.

Tushar
  • 1,117
  • 1
  • 10
  • 25
  • 1
    How does one warn about shadowing with the command-line `go` application? – S.S. Anne Sep 28 '19 at 23:46
  • 1
    Well, go compiler doesn't really have any concept of warnings. Anything `go run` or `go build` finds disturbing will always be an error. There are other tools like `go fmt` & `goimports` that warn about bad coding practices. Most IDEs(Visual Code, Intellij), integrate with them to show warnings. For command-line options, you will need to check the documentations of these 2 commands. – Tushar Sep 29 '19 at 20:26