看起来很简单,但我无法实现。浏览domain.com/post/1
时,应显示行id
中的数据值1
。
行id
是整数 ( int4
)。
在代码下方,这不起作用:
package main
import "fmt"
import "github.com/go-martini/martini"
import "net/http"
import "database/sql"
import _ "github.com/lib/pq"
func SetupDB() *sql.DB {
db, err := sql.Open("postgres", "user=postgres password=apassword dbname=lesson4 sslmode=disable")
PanicIf(err)
return db
}
func PanicIf(err error) {
if err != nil {
panic(err)
}
}
func main() {
m := martini.Classic()
m.Map(SetupDB())
m.Get("/post/:idnumber", func(rw http.ResponseWriter, r *http.Request, db *sql.DB) {
rows, err := db.Query(`SELECT title, author, description FROM books WHERE id = params["idnumber"]`)
PanicIf(err)
defer rows.Close()
var title, author, description string
for rows.Next() {
err:= rows.Scan(&title, &author, &description)
PanicIf(err)
fmt.Fprintf(rw, "Title: %s\nAuthor: %s\nDescription: %s\n\n",
title, author, description)
}
})
m.Run()
}