Golang使用数据库


package main

import (
	"database/sql"
	_ "github.com/go-sql-driver/mysql"
	"log"
	"net/http"
)

func IndexHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path == "/" {
		w.Write([]byte("Index Page"))
	} else {
		w.Write([]byte("404"))
	}
}

func UserHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {

		var ID int
		var username, email string

		err := db.QueryRow("select ID, user_login, user_email from wp_users WHERE ID = 1").Scan(&ID, &username, &email)
		if err != nil {
			log.Print(err)
			return
		}

		w.Write([]byte(username))
	} else {
		w.Write([]byte("User Post"))
	}
}

var db *sql.DB
var err error

func main() {

	db, err = sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/wordpress")
	if err != nil {
		log.Fatalln(err)
	}
	defer db.Close()

	db.SetMaxIdleConns(20)
	db.SetMaxOpenConns(20)

	if err = db.Ping(); err != nil {
		log.Fatalln(err)
	}

	http.HandleFunc("/", IndexHandler)
	http.HandleFunc("/user", UserHandler)
	http.ListenAndServe(":8080", nil)
}