package main
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
"log"
"net/http"
)
func sayHello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello world!")
}
func getUser(w http.ResponseWriter, r *http.Request) {
db, err := sql.Open("sqlite3", "./foo.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
rows, err := db.Query("select * from users where userId=1")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var userId int
var uname string
rows.Next()
rows.Scan(&userId, &uname)
format := `userId : %d uname: %s`
out := fmt.Sprintf(format, userId, uname)
//fmt.Fprintf(w, uname)
fmt.Fprintf(w, out)
}
func main() {
http.HandleFunc("/", sayHello)
http.HandleFunc("/user", getUser)
err := http.ListenAndServe(":8880", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err.Error())
}
}
有疑问加站长微信联系(非本文作者)