<p>Still new to Go, feeling slightly discouraged at being stuck on this pretty trivial little problem.</p>
<pre><code>package main
import (
"fmt"
"net/http"
//"time"
"encoding/json"
"github.com/jinzhu/gorm"
_ "github.com/mattn/go-sqlite3"
"github.com/zenazn/goji"
//"github.com/zenazn/goji/web"
)
type Task struct {
ID int64 `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Code string `json:"code"`
}
var db gorm.DB
func main() {
db, err := gorm.Open("sqlite3", "test.db")
if err != nil {
fmt.Printf("got an error opening the db\n")
}
db.LogMode(true)
db.CreateTable(Task{})
defer db.Close()
goji.Get("/", Root)
goji.Get("/tasks", GetTasks)
goji.Serve()
}
// Root path, does nothing really
func Root(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hi")
}
func GetTasks(w http.ResponseWriter, r *http.Request) {
tasks := []Task{}
db.Find(&tasks)
json.NewEncoder(w).Encode(tasks)
}
</code></pre>
<p>Seems super simple, Goji starts, I've confirmed the db is there, and yet I get a "panic: runtime error: invalid memory address or nil pointer dereference" anytime I hit /tasks; seems like db.Find has a problem. What's up???</p>
<hr/>**评论:**<br/><br/>paukul: <pre><p>You're shadowing the db variable so the global db is still uninitialized. change </p>
<p><code>db, err :=</code>
to
<code>
var err error
db, err =...
</code>
And try again. At least that's my guess. I'm on mobile sorry for the formatting</p></pre>panama_canals: <pre><p>That was 100% the issue; changed to:
db, _ = gorm.Open("sqlite3", "test.db") and it works.
Thanks!</p></pre>ManticoreX: <pre><p>so you don't have to throw away the error, define var err Error on the line prior, and then you can do db, err = gorm....</p></pre>panama_canals: <pre><p>That's what I ended up doing, everything's cool now. I feel like I should be old enough to not be hassled by a scoping issue, but that's life I guess...</p></pre>habeyer: <pre><p>Very frustrating, I do that all the time</p></pre>RalphCorderoy: <pre><p><a href="http://www.qureet.com/blog/golang-beartrap/" rel="nofollow">http://www.qureet.com/blog/golang-beartrap/</a> is one explanation of this problem. (Disclosure: I read a draft.)</p></pre>consigntooblivion: <pre><p>Something I use is to print the object with the %#v format, which dumps the details. In your program I did:</p>
<pre><code>fmt.Printf("\n\n%#v\n\n", db)
</code></pre>
<p>and got:</p>
<pre><code>gorm.DB{Value:interface {}(nil), Error:error(nil), RowsAffected:0, callback:(*gorm.callback)(nil), db:gorm.sqlCommon(nil), parent:(*gorm.DB)(nil), search:(*gorm.search)(nil), logMode:0, logger:gorm.logger(nil), dialect:gorm.Dialect(nil), singularTable:false, source:"", values:map[string]interface {}(nil), joinTableHandlers:map[string]gorm.JoinTableHandler(nil)}
</code></pre>
<p>I find it useful sometimes to see the details of the current value.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传