【Go语言成长之路】使用 Go 和 Gin 开发 RESTful API

2024-08-28 18:28

本文主要是介绍【Go语言成长之路】使用 Go 和 Gin 开发 RESTful API,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 使用 Go 和 Gin 开发 RESTful API
    • 一、前提
    • 二、设计API端点
    • 三、创建项目
    • 四、运行项目
      • 4.1 编写代码
      • 4.2 运行代码

使用 Go 和 Gin 开发 RESTful API

​ 本教程使用Go和 Gin Web Framework (Go语言中优秀的第三方Web框架)编写一个RESTful Web服务API, 实现路由请求、检索请求详细信息、JSON编码响应。

一、前提

  • Go 1.16以及之后的版本
  • curl工具,在Linux和mac中以及内置好了,而在windows中,win10 17063以及之后的版本已经内置该工具,但如果在该版本之前,则需要进行安装

二、设计API端点

​ 本教程将构建一个 API,提供对Album的访问、添加操作。因此,需要提供端点(endPoint),客户端可以通过该端点获取和添加用户的相册。

重要的事:开发 API 时,通常从设计端点开始,端点应该设计的易于理解。

​ 以下是本教程中创建的端点:

  • /albums
    • GET: 获取所有的相册列表,以JSON字符串返回
    • POST: 根据以 JSON 形式发送的请求数据添加新相册
  • /albums/:id
    • GET: 通过ID来获取一个相册,以JSON字符串返回

三、创建项目

首先,将编写的代码创建一个项目

~$ mkdir web-service-gin
~$ cd web-service-gin

其次,创建一个模块来管理依赖:

~/web-service-gin$ go mod init example/web-service-gin
go: creating new go.mod: module example/web-service-gin

此命令创建一个 go.mod 文件,会将需要的依赖项添加到该文件中并且跟踪。

注: 了解更多关于模块依赖管理的信息,请查阅: Managing dependencies

四、运行项目

为了让数据保持简单,本教程将数据存储到内存中进行交互,而在一般更为典型的API将会与数据库(database)进行交互。

注意:将数据存储在内存中意味着每次停止服务器数据都会丢失,然后在启动服务器时重新创建。

4.1 编写代码

使用文本编辑器在 web-service-gin 目录中创建一个名为 main.go 的文件,内容如下:

package mainimport ("net/http""github.com/gin-gonic/gin"
) 
// 1. create album struct, it used to store album data in memory
// album represents data about a record album.
type album struct {// Struct tags such as json:"artist" specify what a field’s name should be// when the struct’s contents are serialized into JSON.// Without them, the JSON would use the struct’s capitalized field names – a style not as common in JSON.ID     string  `json:"id"`Title  string  `json:"title"`Artist string  `json:"artist"`Price  float64 `json:"price"`
}// 2. declare a slice of album structs containing data you'll use to start
// 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},
}// 3.Write a handler to return all items¶
// When the client makes a request at GET /albums, you want to return all the albums as JSON.
// To do this, you’ll write the following:
// 1.Logic to prepare a response
// 2.Code to map the request path to your logic
// This getAlbums function creates JSON from the slice of album structs, writing the JSON into the response.
// getAlbums responds with the list of all albums as JSON.
func getAlbums(c *gin.Context) { // gin.Context is the most important part of Gin. It carries request details, validates and serializes JSON, and more.// The function’s first argument is the HTTP status code you want to send to the client.// Note that you can replace Context.IndentedJSON with a call to Context.JSON to send more compact JSON.// In practice, the indented form is much easier to work with when debugging and the size difference is usually small.c.IndentedJSON(http.StatusOK, albums) //  serialize the struct into JSON and add it to the response.
}// 4.Write a handler to add a new item¶
// When the client makes a POST request at /albums, you want to add the album described in the request body to the existing albums’ data.
// To do this, you’ll write the following:
// 1.Logic to add the new album to the existing list.
// 2.A bit of code to route the POST request to your logic.
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)// Add a 201 status code to the response, along with JSON representing the album you added.c.IndentedJSON(http.StatusCreated, newAlbum)
}// 5. Write a handler to return a specific item¶
// When the client makes a request to GET /albums/[id], you want to return the album whose ID matches the id path parameter.
// getAlbumByID locates the album whose ID value matches the id
// parameter sent by the client, then returns that album as a response.
func getAlbumByID(c *gin.Context) {// Use Context.Param to retrieve the id path parameter from the URL.// When you map this handler to a path, you’ll include a placeholder for the parameter in the path.id := c.Param("id")// Loop over the list of albums, looking for// an album whose ID value matches the parameter.// As mentioned above, a real-world service would likely use a database query to perform this lookup.for _, a := range albums {if a.ID == id {c.IndentedJSON(http.StatusOK, a)return}}// Return an HTTP 404 error with http.StatusNotFound if the album isn’t found.c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"})
}// 6.assign the handler function to an endpoint path.
func main() {// Initialize a Gin router using Default.router := gin.Default()// This sets up an association in which getAlbums handles requests to the /albums endpoint path.router.GET("/albums", getAlbums)// Associate the POST method at the /albums path with the postAlbums function.router.POST("/albums", postAlbums)// In Gin, the colon preceding an item in the path signifies that the item is a path parameter.router.GET("/albums/:id", getAlbumByID)// Use the Run function to attach the router to an http.Server and start the server.router.Run("localhost:8080")
}

4.2 运行代码

  1. 追踪依赖

    使用go get命令获取模块中所需要使用到的依赖

    ~/web-service-gin/$ go get .
    go get: added github.com/gin-gonic/gin v1.7.2
    

    注:使用.代表获取当前目录下的所有依赖

  2. 运行代码

    ~/web-service-gin/$ go run main.go
    [GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.- using env:   export GIN_MODE=release- using code:  gin.SetMode(gin.ReleaseMode)[GIN-debug] GET    /albums                   --> main.getAlbums (3 handlers)
    [GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
    Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
    [GIN-debug] Listening and serving HTTP on localhost:8080
    

    运行成功之后,HTTP服务器就成功启动了,然后就可以发送相应的请求。

  3. 使用curl命令向web服务器发送请求

    • 发送GET的/albums请求

      $ curl http://localhost:8080/albums
      [{"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}
      ]
      
    • 发送POST的/albums请求

      $ 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}'
      HTTP/1.1 201 Created
      Content-Type: application/json; charset=utf-8
      Date: Tue, 27 Aug 2024 15:34:36 GMT
      Content-Length: 116{"id": "4","title": "The Modern Sound of Betty Carter","artist": "Betty Carter","price": 49.99
      }
      
    • 发送带有参数GET的/albums请求

      $ curl http://localhost:8080/albums/2
      {"id": "2","title": "Jeru","artist": "Gerry Mulligan","price": 17.99
      }
      

这篇关于【Go语言成长之路】使用 Go 和 Gin 开发 RESTful API的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1115543

相关文章

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

Java调用DeepSeek API的最佳实践及详细代码示例

《Java调用DeepSeekAPI的最佳实践及详细代码示例》:本文主要介绍如何使用Java调用DeepSeekAPI,包括获取API密钥、添加HTTP客户端依赖、创建HTTP请求、处理响应、... 目录1. 获取API密钥2. 添加HTTP客户端依赖3. 创建HTTP请求4. 处理响应5. 错误处理6.

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

Android 悬浮窗开发示例((动态权限请求 | 前台服务和通知 | 悬浮窗创建 )

《Android悬浮窗开发示例((动态权限请求|前台服务和通知|悬浮窗创建)》本文介绍了Android悬浮窗的实现效果,包括动态权限请求、前台服务和通知的使用,悬浮窗权限需要动态申请并引导... 目录一、悬浮窗 动态权限请求1、动态请求权限2、悬浮窗权限说明3、检查动态权限4、申请动态权限5、权限设置完毕后

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没

在 Spring Boot 中使用 @Autowired和 @Bean注解的示例详解

《在SpringBoot中使用@Autowired和@Bean注解的示例详解》本文通过一个示例演示了如何在SpringBoot中使用@Autowired和@Bean注解进行依赖注入和Bean... 目录在 Spring Boot 中使用 @Autowired 和 @Bean 注解示例背景1. 定义 Stud

使用 sql-research-assistant进行 SQL 数据库研究的实战指南(代码实现演示)

《使用sql-research-assistant进行SQL数据库研究的实战指南(代码实现演示)》本文介绍了sql-research-assistant工具,该工具基于LangChain框架,集... 目录技术背景介绍核心原理解析代码实现演示安装和配置项目集成LangSmith 配置(可选)启动服务应用场景

使用Python快速实现链接转word文档

《使用Python快速实现链接转word文档》这篇文章主要为大家详细介绍了如何使用Python快速实现链接转word文档功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 演示代码展示from newspaper import Articlefrom docx import

oracle DBMS_SQL.PARSE的使用方法和示例

《oracleDBMS_SQL.PARSE的使用方法和示例》DBMS_SQL是Oracle数据库中的一个强大包,用于动态构建和执行SQL语句,DBMS_SQL.PARSE过程解析SQL语句或PL/S... 目录语法示例注意事项DBMS_SQL 是 oracle 数据库中的一个强大包,它允许动态地构建和执行