我有这样的代码:
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)
}
}
我以为我可以db在booksIndex设置为全局变量时访问。当我将数据库初始化移动到booksIndex错误时不会出现。
我的代码中有哪些部分有问题?
另外,我是 Golang 的新手。如果您对如何组织我的代码有任何建议,请告诉我。谢谢.. :)
慕村9548890
相关分类