用Go编写的RESTful API与Gin(附代码)

101 阅读1分钟

web-service-gin

forthebadge made-with-go

用Go和Gin编写的RESTful API。

API返回关于复古爵士乐记录的数据。

端点

  • /albums

    • GET - 获取所有专辑的列表,以JSON格式返回。
    • POST - 从以JSON格式发送的请求数据中添加一个新的专辑。
  • /albums/:id

    • GET - 通过其ID获取专辑,以JSON格式返回专辑数据。

前提条件

  • 安装Go 1.16或更高版本:有关安装说明,请参阅安装Go。

  • 一个编辑代码的工具:您拥有的任何文本编辑器都可以工作。

  • 一个命令终端:在 Linux 和 Mac 上使用任何终端,以及在 Windows 上使用 PowerShell 或 cmd,Go 都能很好地工作。

  • curl工具:在Linux和Mac上,这个工具应该已经安装。在Windows上,它包含在Windows 10 Insider build 17063及以后的版本中。对于早期的Windows版本,你可能需要安装它。更多信息,请看Tar 和 Curl 来到 Windows。

设置

git clone https://github.com/Sarthak2143/web-service-gin
cd web-service-gin/
go get .
go run .

它在localhost:8080 上启动了网络服务器。

实例

  • 获取所有相册
curl http://localhost:8080
[                                                        {        "id": "1",                                           "title": "After Dark",        "artist": "Mr. Kitty",                               "Price": 56.99                                   },    {                                                        "id": "2",        "title": "Where is my mind?",        "artist": "Pixies",        "Price": 59.99    },    {                                                        "id": "3",        "title": "Sarah Vaughan and Clifford Brown",        "artist": "Sarah Vaughan",        "Price": 48.99    }]                                                  {
        
  • 添加一个相册
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: Wed, 02 Jun 2021 00:34:12 GMT
Content-Length: 116
{
    "id": "4",
    "title": "The Modern Sound of Betty Carter",
    "artist": "Betty Carter",
    "price": 49.99
}
    
  • 通过以下方式获取一个相册ID
curl http://localhost:8080/albums/2
{
    "id": "2",
    "title": "Where is my mind?",
    "artist": "Pixies",
    "Price": 59.99
}