我有这样的代码:
package main
import (
"database/sql"
"flag"
"fmt"
"log"
"net/http"
"os"
_ "github.com/go-sql-driver/mysql"
)
// Default constant for configuration
const DefaultHTTPAddr = ":8080"
const DefaultDSN = "root:root@tcp(127.0.0.1:3306)/librarian"
// Parameters
var (
httpAddr string
dsn string
db *sql.DB
)
// init initializes this package.
func init() {
flag.StringVar(&httpAddr, "addr", DefaultHTTPAddr, "Set the HTTP bind address")
flag.StringVar(&dsn, "dsn", DefaultDSN, "Set the Data Source Name")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s [options]\n", os.Args[0])
flag.PrintDefaults()
}
}
type Book struct {
id int
title string
author string
}
func main() {
flag.Parse()
var err error
db, err := sql.Open("mysql", DefaultDSN)
if err != nil {
log.Fatal(err)
}
if err = db.Ping(); err != nil {
log.Fatal(err)
}
// handler
http.HandleFunc("/", homepage)
http.HandleFunc("/books", booksIndex)
log.Println("httpd started successfully")
http.ListenAndServe(httpAddr, nil)
}
func booksIndex(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, http.StatusText(405), 405)
return
}
rows, err := db.Query("SELECT * FROM books")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
books := make([]*Book, 0)
for rows.Next() {
bk := new(Book)
err = rows.Scan(&bk.id, &bk.title, &bk.author)
if err != nil {
log.Fatal(err)
}
books = append(books, bk)
}
if err = rows.Err(); err != nil {
log.Fatal(err)
}
for _, bk := range books {
fmt.Fprintf(w, "%v, %v, %v\n", bk.id, bk.title, bk.author)
}
}
func homepage(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome!")
}
每次我尝试访问 /books 时,它总是会崩溃。
$ curl localhost:8080/books
curl: (52) Empty reply from server
像这个:
2016/05/31 11:56:38 http: panic serving 127.0.0.1:51711: runtime error: invalid memory address or nil pointer dereference
goroutine 6 [running]:
net/http.(*conn).serve.func1(0xc820074100)
/usr/local/opt/go/libexec/src/net/http/server.go:1389 +0xc1
panic(0x357b40, 0xc82000a150)
/usr/local/opt/go/libexec/src/runtime/panic.go:443 +0x4e9
database/sql.(*DB).conn(0x0, 0xc820010b01, 0xc8200de000, 0x0, 0x0)
/usr/local/opt/go/libexec/src/database/sql/sql.go:778 +0xac9
database/sql.(*DB).query(0x0, 0x4022c0, 0x13, 0x0, 0x0, 0x0, 0x3c4601, 0x6, 0x0, 0x0)
/usr/local/opt/go/libexec/src/database/sql/sql.go:1073 +0x46
database/sql.(*DB).Query(0x0, 0x4022c0, 0x13, 0x0, 0x0, 0x0, 0xc820016280, 0x0, 0x0)
/usr/local/opt/go/libexec/src/database/sql/sql.go:1061 +0xa3
main.booksIndex(0x6979c0, 0xc82006da00, 0xc8200e2000)
/Users/rahmatawaludin/gocode/src/github.com/rahmatawaludin/librarian/main.go:68 +0xd9
net/http.HandlerFunc.ServeHTTP(0x4666f8, 0x6979c0, 0xc82006da00, 0xc8200e2000)
/usr/local/opt/go/libexec/src/net/http/server.go:1618 +0x3a
net/http.(*ServeMux).ServeHTTP(0xc820010ba0, 0x6979c0, 0xc82006da00, 0xc8200e2000)
/usr/local/opt/go/libexec/src/net/http/server.go:1910 +0x17d
net/http.serverHandler.ServeHTTP(0xc820074080, 0x6979c0, 0xc82006da00, 0xc8200e2000)
/usr/local/opt/go/libexec/src/net/http/server.go:2081 +0x19e
net/http.(*conn).serve(0xc820074100)
/usr/local/opt/go/libexec/src/net/http/server.go:1472 +0xf2e
created by net/http.(*Server).Serve
/usr/local/opt/go/libexec/src/net/http/server.go:2137 +0x44e
我认为我可以从 booksIndex 访问 db,因为我将其设置为全局变量。当我将数据库初始化移动到 booksIndex 时,错误没有显示出来。
我的代码中哪些部分有问题?
此外,我是 Golang 的新手。如果您对如何组织我的代码有任何建议,请告诉我。谢谢..:)
最佳答案
函数中的 db 变量正在隐藏全局变量。 当您这样做时:
db,err:=
它将它分配给一个新的局部变量db。 这是因为它不是来自同一 block 。根据标准:
Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block (or the parameter lists if the block is the function body) with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration. Redeclaration does not introduce a new variable; it just assigns a new value to the original.
所以全局变量仍然是 nil 指针。当它被访问时,你会得到 nil 指针解引用
将其更改为 d,然后将其分配给 db。或者哪个更正确(如 rahmat 在评论中给出的那样):=
d , err =
我建议您为处理程序、模型等创建单独的文件。并查看 https://github.com/mattermost/platform如何组织代码。
关于database - 为什么无法从处理程序访问我的数据库连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37537156/
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack
为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返
我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在
我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r
我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e