package main
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
"log"
"net/http"
)
// User is user
type User struct {
ID int
Name string
}
func (user User) String() string {
format := `ID : %d Name: %s`
return fmt.Sprintf(format, user.ID, user.Name)
}
func sayHello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello world!")
}
func GetUsers() string {
db, err := sql.Open("sqlite3", "./foo.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
rows, err := db.Query("select * from users")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var id, name string
users := ""
for rows.Next() {
err = rows.Scan(&id, &name)
if err == nil {
log.Println(id, name)
users = users + id + "," + name + ";\n"
}
}
return users
}
func getUsers(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, GetUsers())
}
func main() {
http.HandleFunc("/", sayHello)
http.HandleFunc("/users", getUsers)
err := http.ListenAndServe(":8880", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err.Error())
}
}
有疑问加站长微信联系(非本文作者)