From 06a9726bca094e69d15018bf359914744f6cb64b Mon Sep 17 00:00:00 2001 From: asahi Date: Tue, 7 Jan 2025 23:41:43 +0800 Subject: [PATCH] =?UTF-8?q?=E9=98=85=E8=AF=BBgolang=20gin=20restful?= =?UTF-8?q?=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Golang/Golang Document.md | 53 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/Golang/Golang Document.md b/Golang/Golang Document.md index 5538304..e783162 100644 --- a/Golang/Golang Document.md +++ b/Golang/Golang Document.md @@ -47,3 +47,56 @@ use ( - 如果指定目录存在,会为`dir`向`go.work`文件中添加一条use指令 - 如果指定目录不存在,会删除`go.work`文件中关于目录的use指令 +## Gin框架构建restful api +在构建resultful api时,通常都会通过json格式来传递数据,首先,可定义业务实体: +```go +// 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"` +} +``` + +### 向response中写入返回数据 +可以通过调用`gin.Context`的`IndentedJSON`方法来向response中写入数据, +```go +// getAlbums responds with the list of all albums as JSON. +func getAlbums(c *gin.Context) { + c.IndentedJSON(http.StatusOK, albums) +} +``` + +### 解析request中的数据 +可以通过`gin.Context`的`BindJSON`方法来将请求体中的数据解析到对象中。 +```go +// 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) +} +``` + +### 将请求的endpoint注册到server中 +可以将各个请求的处理handler注册到server中,并在指定端口上运行server: +```go +func main() { + router := gin.Default() + router.GET("/albums", getAlbums) + router.POST("/albums", postAlbums) + + router.Run("localhost:8080") +} +``` +上述示例中,分别向`/albums`路径注册了GET和POST的处理handler,并在`localhost:8080`上对服务进行监听。 +