本文共 3645 字,大约阅读时间需要 12 分钟。
package main
import (
"log"
"fmt"
"encoding/json"
"net/http"
"database/sql"
_ "github.com/go-sql-driver/mysql"
"goji.io"
"goji.io/pat"
)
// CREATE DATABASE IF NOT EXISTS `book` DEFAULT CHARSET utf8;
/* CREATE TABLE IF NOT EXISTS `books` (
`id` int(11) NOT NULL auto_increment,
`bname` varchar(255) NOT NULL default '',
PRIMARY KEY (`id`)
); */
type Book struct {
Id int `json:"bookid"`
Bname string `json:"bookname"`
}
var db *sql.DB
func init() {
_db, err := sql.Open("mysql", "root:root@tcp(localhost:3306)/book")
if (err != nil) {
log.Println(err)
}
err = _db.Ping()
if err != nil {
log.Fatal(err)
}
db = _db
}
func ErrorWithJSON(w http.ResponseWriter, message string, code int) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(code)
fmt.Fprintf(w, "{message: %q}", message)
}
func ResponseWithJSON(w http.ResponseWriter, json []byte, code int) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(code)
w.Write(json)
}
func main() {
mux := goji.NewMux()
mux.HandleFunc(pat.Get("/book"), allBook)
mux.HandleFunc(pat.Post("/book"), addBook)
mux.HandleFunc(pat.Get("/book/:id"), bookById)
mux.HandleFunc(pat.Put("/book/:id"), updateBookById)
mux.HandleFunc(pat.Delete("/book/:id"), deleteBookById)
http.ListenAndServe("localhost:8080", mux)
defer db.Close()
}
// curl -X GET -H "Content-Type: application/json" http://localhost:8080/book
func allBook(w http.ResponseWriter, r *http.Request) {
rows,err := db.Query("SELECT * FROM `books`")
if err != nil {
log.Println(err)
} else {
defer rows.Close()
var books []Book
for i:=0; rows.Next(); i++ {
books = append(books, Book{})
err = rows.Scan(&books[i].Id, &books[i].Bname)
if err != nil {
log.Println(err)
}
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
respBody,_ := json.MarshalIndent(books, "", " ")
ResponseWithJSON(w, respBody, http.StatusOK)
}
}
// curl -X POST -H "Content-Type: application/json" -d '{"bookname": "20suigandianshenme"}' http://localhost:8080/book
func addBook(w http.ResponseWriter, r *http.Request) {
var book Book
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&book)
if err != nil {
ResponseWithJSON(w, []byte("{"status":"fail"}"), http.StatusBadRequest)
return
}
_,err = db.Exec(
"INSERT INTO `books` (bname) VALUES (?)",
book.Bname,
)
if err != nil {
log.Fatal(err)
}
ResponseWithJSON(w, []byte("{"status":"ok"}"), http.StatusOK)
}
// curl -X GET -H "Content-Type: application/json" http://localhost:8080/book/1
func bookById(w http.ResponseWriter, r *http.Request) {
var book Book
bookid := pat.Param(r, "id")
row := db.QueryRow(
"SELECT * FROM `books` WHERE id=?",
bookid,
)
row.Scan(&book.Id, &book.Bname)
respBody,_ := json.MarshalIndent(book, "", " ")
ResponseWithJSON(w, respBody, http.StatusOK)
}
// curl -X DELETE -H "Content-Type: application/json" http://localhost:8080/book/1
func deleteBookById(w http.ResponseWriter, r *http.Request) {
bookid := pat.Param(r, "id")
_,err := db.Exec(
"DELETE FROM `books` WHERE id=?",
bookid,
)
if err != nil {
log.Fatal(err)
}
ResponseWithJSON(w, []byte("{"status":"ok"}"), http.StatusOK)
}
// curl -X PUT -H "Content-Type: application/json" -d '{"bookname": "test"}' http://localhost:8080/book/2
func updateBookById(w http.ResponseWriter, r *http.Request) {
var book Book
bookid := pat.Param(r, "id")
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&book)
if err != nil {
ResponseWithJSON(w, []byte("{"status":"fail"}"), http.StatusBadRequest)
return
}
_,err = db.Exec(
"UPDATE `books` SET bname=? WHERE id=?",
book.Bname,
bookid,
)
if err != nil {
log.Fatal(err)
}
ResponseWithJSON(w, []byte("{"status":"ok"}"), http.StatusOK)
}
转载地址:http://yfnzx.baihongyu.com/