博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mysql微服务_go Gojj+Mysql搭建微服务-Go语言中文社区
阅读量:5742 次
发布时间:2019-06-18

本文共 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/

你可能感兴趣的文章
影响网站排名的因素
查看>>
Hyper-v下安装网络流量监测图形分析工具 Cacti
查看>>
Innodb逻辑存储
查看>>
Windows Server 2008搭建域环境---安装活动目录
查看>>
笑傲江湖-神雕侠侣
查看>>
php中引用&的真正理解-变量引用、函数引用、对象引用
查看>>
关于跨域请求的问题
查看>>
REDHAT5 配置dhcp服务器
查看>>
IIS 内部运行机制
查看>>
ASP.NET MVC Bundling and RequireJS
查看>>
ansible 的Playbook
查看>>
test title9
查看>>
Linux的配置数据库服务器
查看>>
Java之品优购课程讲义_day15(2)
查看>>
Linux 工具
查看>>
Mybatis学习笔记-动态SQL与模糊查询
查看>>
Linux下实用的排错安全工具打包推荐
查看>>
hadoop2.0 snappy 压缩的安装和配置
查看>>
phantomjs1-访问百度获取标题
查看>>
django加密解密api
查看>>