作为 Go 新手,光看语法很难真正掌握编程。通过实践一个小项目,你可以同时了解 Go 基础语法、数据库操作和 Web 开发。
数据库设计
CREATE DATABASE IF NOT EXISTS music_store;
USE music_store;
CREATE TABLE IF NOT EXISTS albums (
id VARCHAR(255) NOT NULL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
artist VARCHAR(255) NOT NULL,
price DECIMAL(10,2) NOT NULL
);
INSERT INTO albums (id, title, artist, price) VALUES
('1', 'Blue Train', 'John Coltrane', 56.99),
('2', 'Jeru', 'Gerry Mulligan', 17.99),
('3', 'Sarah Vaughan and Clifford Brown', 'Sarah Vaughan', 39.99);
代码示例
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
// Album 定义音乐专辑的数据模型
type Album struct {
ID string `json:"id" gorm:"primaryKey"` // 主键
Title string `json:"title"` // 专辑标题
Artist string `json:"artist"` // 艺术家
Price float64 `json:"price"` // 价格
}
var db *gorm.DB
var err error
func initDB() {
dsn := "root:123456@tcp(127.0.0.1:3306)/music_store"
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{}) // 连接数据库
if err != nil {
fmt.Println("连接数据库失败:", err)
panic("连接数据库失败")
}
}
func main() {
initDB() // 初始化数据库连接
router := gin.Default() // 创建 Gin 路由实例
// 路由定义
router.GET("/albums", getAlbums) // 获取所有专辑
router.GET("/albums/:id", getAlbumByID) // 根据 ID 获取专辑
router.POST("/albums", postAlbum) // 创建新专辑
router.Run("localhost:8080") // 启动 HTTP 服务
}
// 获取所有专辑
func getAlbums(c *gin.Context) {
var albums []Album
db.Find(&albums) // 查询所有专辑
c.IndentedJSON(http.StatusOK, albums) // 返回 JSON
}
// 根据 ID 获取专辑
func getAlbumByID(c *gin.Context) {
id := c.Param("id") // 获取 URL 参数
var album Album
db.First(&album, "id = ?", id) // 查询指定 ID 的专辑
c.IndentedJSON(http.StatusOK, album) // 返回 JSON
}
// 创建新专辑
func postAlbum(c *gin.Context) {
var newAlbum Album
c.BindJSON(&newAlbum) // 解析请求 JSON
db.Create(&newAlbum) // 插入数据库
c.IndentedJSON(http.StatusCreated, newAlbum) // 返回创建结果
}
测试 API
启动服务后,可使用 curl 测试接口:
- 获取所有专辑:
curl http://localhost:8080/albums
- 获取单个专辑:
curl http://localhost:8080/albums/2
- 新增专辑:
curl -X POST http://localhost:8080/albums \
-H "Content-Type: application/json" \
-d '{"id":"4","title":"New Album","artist":"New Artist","price":29.99}'