# Go-Gin-WebServer **Repository Path**: CPLASF000000/go-gin-web-server ## Basic Information - **Project Name**: Go-Gin-WebServer - **Description**: 基于官方案例的我的第一个支持RESTful api的go 服务 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-07-17 - **Last Updated**: 2024-08-03 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 如何使用Go来快速实现一个 RESTful api 服务 这里采用[官方文档](https://golang.google.cn/doc/tutorial/web-service-gin)的例子 ## import 包 ```go import ( "net/http" "github.com/gin-gonic/gin" ) ``` ## ## 所有代码 ```go package main import ( "net/http" "github.com/gin-gonic/gin" ) // 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"` } // albums slice to seed record album data. var albums = []album{ {ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99}, {ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99}, {ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99}, } // getAlbums responds with the list of all albums as JSON. func getAlbums(c *gin.Context) { c.IndentedJSON(http.StatusOK, albums) } // postAlbums adds an album from JSON received in the request body. func postAlbums(c *gin.Context) { var newAlbum album // Call BindJSON to bind the received JSON to // newAlbum. if err := c.BindJSON(&newAlbum); err != nil { return } // Add the new album to the slice. albums = append(albums, newAlbum) c.IndentedJSON(http.StatusCreated, newAlbum) } func main() { router := gin.Default() router.GET("/albums", getAlbums) router.POST("/albums", postAlbums) router.Run("localhost:8080") } ``` ## 测试 ### 测试 get 请求 ```bash curl http://localhost:8080/albums ``` ### 测试 post 请求 ```bash curl http://localhost:8080/albums \ --include \ --header "Content-Type: application/json" \ --request "POST" \ --data '{"id": "4","title": "The Modern Sound of Betty Carter","artist": "Betty Carter","price": 49.99}' ``` ## 如何部署? docker部署,虚拟机部署,然后用windows pc 客户端来测试访问 ## 总结 一个简单的 RESTful api 就弄好了 但是太简单了,很多功能都没有,实际用的话不够的 实际还需要用到的功能: 1. 用户分级,token鉴权 2. 错误码返回 3. 数据库查询 4. 上传和下载 数据或文件