du1068 2018-04-26 18:16
浏览 37
已采纳

大猩猩Mux和GORM失败

I followed this tutorial on how to setup a basic API with PostgreSQL, Gorilla Mux and GORM.

This is my app:

package main

import (
    "encoding/json"
    "net/http"

    "github.com/gorilla/mux"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/postgres"
)

var db *gorm.DB


type Ticket struct {
    gorm.Model
    InfoHash string
    Status   *int `gorm:"default:'0'"`
}


func main() {
    router := mux.NewRouter()

    db, err := gorm.Open("postgres", "host=localhost user=user dbname=db_development password=password sslmode=disable")
    db.LogMode(true)

    if err != nil {
        panic(err)
    }
    defer db.Close()

    db.AutoMigrate(&Ticket{})

    router.HandleFunc("/", TicketsIndex).Methods("GET")

    http.ListenAndServe(":3000", router)
}

func TicketsIndex(w http.ResponseWriter, r *http.Request) {
    tickets := []Ticket{}
    db.Find(&tickets)
    json.NewEncoder(w).Encode(&tickets)
}

The problem is when I visit localhost:3000, the server just stops with no error logs, just stops and exit the app. It should return the tickets stored in the database as JSON.

I got it working if I open the database in my TicketsIndex function and close it, like this:

func TicketsIndex(w http.ResponseWriter, r *http.Request) {
  db, err := gorm.Open("postgres", "host=localhost user=user dbname=db_development password=password sslmode=disable")
  tickets := []Ticket{}
  db.Find(&tickets)
  json.NewEncoder(w).Encode(&tickets)
  defer db.Close()
}

But I think this is not the proper way. I also try to move this code into the main function and also works:

tickets := []Ticket{}
db.Find(&tickets)

So I am assuming it could be the global variable var db *gormDB that is not being assigned correctly. What am I doing wrong?

  • 写回答

1条回答 默认 最新

  • doutian4046 2018-04-26 21:48
    关注

    When you type db, err := ... you're actually shadowing the global var db with a function-local variable named db, not assigning to the global one. You need to use the equal sign (= vs :=) to assign to an already defined var. That also means you'll need to write var err error inside of main scope before the assignment, since you're no longer getting declaration automatically from :=.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 不懂得怎么运行下载来的代码
  • ¥15 CST导出3D模型图为什么和软件显示不一样?
  • ¥15 加热反应炉PLC控制系统设计(相关搜索:梯形图)
  • ¥15 python 用Dorc包报错,我的写法和网上教的是一样的但是它显示无效参数,是什么问题
  • ¥15 经过滑动平均后的一维信号还原用什么结构好呢?
  • ¥15 指定IP电脑的访问设置
  • ¥30 matlab ode45 未发现警告,但是运行出错
  • ¥15 为什么devc++编译项目会失败啊
  • ¥15 vscode platformio
  • ¥15 代写uni代码,app唤醒