package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"os"
"strconv"
"github.com/go-sql-driver/mysql"
"github.com/gin-gonic/gin"
)
var db *sql.DB
// album represents data about a record album.
type Album struct {
ID string `json:"id"`
Title string `json:"title"`
Artist string `json:"artist"`
Price float64 `json:"price"`
}
func main() {
// db config
cfg := mysql.Config{
User: os.Getenv("DBUSER"), //export DBUSER=你的 MySQL 用戶名
Passwd: os.Getenv("DBPASS"), //export DBPASS=你的 MySQL password
Net: "tcp",
Addr: "127.0.0.1:3306",
DBName: "recordings",
}
// 連接資料庫
var err error
db, err = sql.Open("mysql", cfg.FormatDSN())
if err != nil {
log.Fatal(err)
}
pingErr := db.Ping() // 確認是否真的連接上資料庫
if pingErr != nil {
log.Fatal(pingErr)
}
fmt.Println("Connected!")
// router 的部分
router := gin.Default()
router.GET("/albums", getAlbums)
router.POST("/albums", postAlbums)
router.GET("/albums/:id", getAlbumByID)
router.Run("localhost:8080")
}
// 取得所有專輯資料
func getAlbums(c *gin.Context) {
var albums []Album
rows, err := db.Query("SELECT * FROM album")
if err != nil {
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "getAlbums error"})
}
defer rows.Close()
for rows.Next() {
var alb Album
if err := rows.Scan(&alb.ID, &alb.Title, &alb.Artist, &alb.Price); err != nil {
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "getAlbums error"})
}
albums = append(albums, alb)
}
if err := rows.Err(); err != nil {
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "getAlbums error"})
}
c.IndentedJSON(http.StatusOK, albums)
}
// 新增專輯
func postAlbums(c *gin.Context) {
var newAlbum Album
// 把接收到的 json body 轉換成 struct
if err := c.BindJSON(&newAlbum); err != nil {
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "getAlbums error"})
}
result, err := db.Exec("INSERT INTO album (title, artist, price) VALUES (?, ?, ?)", newAlbum.Title, newAlbum.Artist, newAlbum.Price)
if err != nil {
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "getAlbums error"})
}
id, err := result.LastInsertId()
if err != nil {
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "getAlbums error"})
}
c.IndentedJSON(http.StatusCreated, "新專輯的 id 是:"+strconv.Itoa(int(id)))
}
// 使用 id 取得特定專輯
func getAlbumByID(c *gin.Context) {
id := c.Param("id")
var alb Album
row := db.QueryRow("SELECT * FROM album WHERE id = ?", id)
if err := row.Scan(&alb.ID, &alb.Title, &alb.Artist, &alb.Price); err != nil {
if err != nil {
c.IndentedJSON(http.StatusNotFound, gin.H{"message": err})
}
}
c.IndentedJSON(http.StatusOK, alb)
}