如何使用GO和Nitric创建您的第一个API | Nitric和GO教程

2,112次阅读
没有评论

共计 7352 个字符,预计需要花费 19 分钟才能阅读完成。

今天,我们将深入研究一个令人兴奋的项目,我们将使用 Nitric 和 GO 创建一个 Profile Management API。

该 API 将处理用户配置文件的创建、更新和删除。然后我们将扩展它来管理个人资料图像。

Method Route Description
GET /profiles/[id] 通过 ID 获取特定配置文件
GET /profiles 列出所有配置文件
POST /profiles 创建新的个人资料
DELETE /profiles/[id] 删除个人资料
PUT /profiles/[id] 更新个人资料
Method Route Description
GET /profiles/[id]/image/upload 获取个人资料图片上传 URL
GET profiles/[id]/image/download 获取个人资料图片下载 URL
GET profiles/[id]/image/view 查看下载的图片

前提条件

  • Go(https://go.dev/dl/

  • Nitric CLI(https://nitric.io/docs/guides/getting-started/installation

  • AWS (https://aws.amazon.com/)、GCP(https://cloud.google.com/)或 Azure 帐户(https://azure.microsoft.com/)(您的选择)

Nitric 介绍

Nitric 是一款工具,可帮助开发人员快速创建云应用程序(例如 AWS、Google Cloud 或 Microsoft Azure),并减少重复代码。它充当代码和云服务之间的桥梁,使构建和部署应用程序变得非常简单。

通过使用 Nitric,您可以更多地专注于构建应用程序,而不是关注云提供商的细节,并消除部署它所需的 Terraform(或其他 IaC)项目。

通过查看我的其他一些博客或访问文档来了解更多信息。(https://nitric.io/docs)

开始

我们首先为 API 创建一个新项目。

nitric new

创建一个项目,为其命名并选择您喜欢的入门模板。

? What is the name of the project? my-profile-api
? Choose a template: official/Go - Starter

接下来,在您选择的编辑器中打开项目。

cd my-profile-api

确保所有依赖项均已解决:

go mod tidy

脚手架项目应具有以下结构:

+--functions/
|  +-- hello/
|      +-- main.go
|  ...
+--nitric.yaml
+--go.mod
+--go.sum
+--.gitignore
+--README.md

您可以测试该项目以验证一切是否按预期工作:

nitric start

并在一个单独的终端中:

go run functions/hello

第一个命令使用 启动 Nitric Server nitric start,它
提供本地接口来模拟云资源。然后运行您的函数并允许它们连接。go run functions/hello

如果一切正常,您现在可以删除 functions/ 文件夹中的所有文件,我们将在本指南中创建新功能。

构建配置文件 API

让我们开始构建配置文件 API。main.go 在函数目录中创建一个名为的文件并添加以下内容:

package main

import (
  "fmt"

  "github.com/nitrictech/go-sdk/nitric"
)

func main() {profilesApi, err := nitric.NewApi("public")
  if err != nil {return}

  profiles, err := nitric.NewCollection("profiles").With(nitric.CollectionReading, nitric.CollectionWriting)
  if err != nil {return}

  if err := nitric.Run(); err != nil {fmt.Println(err)
  }
}

我们在这里创建:

从这里开始,我们向该函数添加一些功能,以便我们可以使用配置文件。

如果您愿意,您可以将部分或全部请求处理程序分离到它们自己的函数中。为简单起见,我们将在本指南中将它们组合在一起

使用 POST 创建配置文件

profilesApi.Post("/profiles", func(ctx *faas.HttpContext, next faas.HttpHandler) (*faas.HttpContext, error) {id := uuid.New().String()

  var profileRequest map[string]interface{}
  err := json.Unmarshal(ctx.Request.Data(), &profileRequest)
  if err != nil {return ctx, err}

  err = profiles.Doc(id).Set(ctx.Request.Context(), profileRequest)
  if err != nil {return ctx, err}

  ctx.Response.Body = []byte(id)

  return ctx, nil
})

使用 GET 检索配置文件

profilesApi.Get("/profiles/:id", func(ctx *faas.HttpContext, next faas.HttpHandler) (*faas.HttpContext, error) {id := ctx.Request.PathParams()["id"]

  profile, err := profiles.Doc(id).Get(ctx.Request.Context())
  if err != nil {
    ctx.Response.Status = 404
    ctx.Response.Body = []byte(fmt.Sprintf("profile with id'%s'not found", id))

    return ctx, nil
  }

  ctx.Response.Body, err = json.Marshal(profile.Content())

  return ctx, err
})

使用 GET 列出所有配置文件

profilesApi.Get("/profiles", func(ctx *faas.HttpContext, next faas.HttpHandler) (*faas.HttpContext, error) {profiles, err := profiles.Query().Fetch(ctx.Request.Context())
  if err != nil {return ctx, err}

  var profileContent []map[string]interface{}
  for _, doc := range profiles.Documents {profileContent = append(profileContent, doc.Content())
  }

  ctx.Response.Body, err = json.Marshal(profileContent)

  return ctx, err
})

使用 DELETE 删除配置文件

profilesApi.Delete("/profile/:id", func(ctx *faas.HttpContext, next faas.HttpHandler) (*faas.HttpContext, error) {id := ctx.Request.PathParams()["id"]

  err := profiles.Doc(id).Delete(ctx.Request.Context())
  if err != nil {
    ctx.Response.Status = 404
    ctx.Response.Body = []byte(fmt.Sprintf("profile with id'%s'not found", id))

    return ctx, nil
  }

  return ctx, nil
})

好吧,让我们运行这个东西!

现在您已经定义了一个 API,并为其每个方法定义了处理程序,是时候在本地测试它了。

nitric start

并在一个单独的终端中:

go run functions/hello

一旦启动,应用程序将通过 API 端口接收请求。您可以使用 cURL、Postman 或任何其他 HTTP 客户端来测试 API。

我们将保持它运行以进行测试。如果您想更新功能,只需保存它们,它们就会自动重新加载。

测试你的 API

如果您在云上进行测试,请更新括号中的所有值 [] 并将 URL 更改为您部署的 URL。

创建个人资料

curl --location --request POST 'http://localhost:4001/profiles' 
--header 'Content-Type: text/plain' 
--data-raw '{"name":"Peter Parker","age":"21","homeTown":"Queens"}'

获取个人资料

curl --location --request GET 'http://localhost:4001/profiles/[id]'

获取所有配置文件

curl --location --request GET 'http://localhost:4001/profiles'

删除个人资料

curl --location --request DELETE 'http://localhost:4001/profiles/[id]'

部署到云端

此时,您可以将构建的内容部署到任何受支持的云提供商。为此,首先设置您的凭据以及您喜欢的云的任何配置:

  • AWS(https://nitric.io/docs/reference/providers/aws)

  • 天蓝色(https://nitric.io/docs/reference/providers/azure)

  • GCP(https://nitric.io/docs/reference/providers/gcp)

接下来,我们需要创建一个 stack. 堆栈表示应用程序的已部署实例,它是项目中定义的资源的集合。您可能需要为每个环境使用单独的堆栈,例如 dev、test 和 的堆栈 prod。现在,让我们从创建 dev 堆栈开始。

nitric stack new
? What do you want to call your new stack? dev
? Which Cloud do you wish to deploy to? aws
? select the region us-east-1

AWS

注意:您有责任遵守免费套餐的限制或与部署相关的任何费用。

我们调用了我们的堆栈 dev,让我们尝试使用 up 命令部署它

nitric up
┌───────────────────────────────────────────────────────────────┐
| API  | Endpoint                                               |
| main | https://XXXXXXXX.execute-api.us-east-1.amazonaws.com   |
└───────────────────────────────────────────────────────────────┘

部署完成后,转到相关的云控制台,您将能够查看您的 API 并与之交互。

要从云中拆除您的应用程序,请使用以下 down 命令:

nitric down

可选 – 添加个人资料图片上传 / 下载支持

如果您想更深入地了解并使用 Nitric 创建一些其他资源,为什么不将图像添加到您的配置文件 API 中。

使用权限访问配置文件存储桶

定义一个 profilesImg 具有读 / 写权限的命名桶

profileImages, err := nitric.NewBucket("profileImages").With(nitric.BucketReading, nitric.BucketWriting)
if err != nil {fmt.Println(err)
  return
}

获取上传个人资料图片的 URL

profilesApi.Get("/profiles/:id/image/upload", func(ctx *faas.HttpContext, next faas.HttpHandler) (*faas.HttpContext, error) {id := ctx.Request.PathParams()["id"]
  photoId := fmt.Sprintf("images/%s/photo.png", id)

  photoUrl, err := profileImages.File(photoId).UploadUrl(ctx.Request.Context(), 600)
  if err != nil {return ctx, err}

  ctx.Response.Body = []byte(photoUrl)

  return ctx, nil
})

获取下载个人资料图片的 URL

profilesApi.Get("/profiles/:id/image/download", func(ctx *faas.HttpContext, next faas.HttpHandler) (*faas.HttpContext, error) {id := ctx.Request.PathParams()["id"]
  photoId := fmt.Sprintf("images/%s/photo.png", id)

  photoUrl, err := profileImages.File(photoId).DownloadUrl(ctx.Request.Context(), 600)
  if err != nil {return ctx, err}

  ctx.Response.Body = []byte(photoUrl)

  return ctx, nil
})

您也可以直接重定向到照片 URL。

profilesApi.Get("/profiles/:id/image/view", func(ctx *faas.HttpContext, next faas.HttpHandler) (*faas.HttpContext, error) {id := ctx.Request.PathParams()["id"]
  photoId := fmt.Sprintf("images/%s/photo.png", id)

  photoUrl, err := profileImages.File(photoId).DownloadUrl(ctx.Request.Context(), 600)
  if err != nil {return ctx, err}

  ctx.Response.Status = 303
  ctx.Response.Headers["Location"] = []string{photoUrl}

  return ctx, nil
})

是时候测试更新的 API 了

如果您在云上进行测试,请更新括号中的所有值 [] 并将 URL 更改为您部署的 URL。

获取图片上传 URL

curl --location --request GET 'http://localhost:4001/profiles/[id]/image/upload'

通过 curl 使用上传 URL

curl --location --request PUT '[url]' --header 'content-type: image/png' --data-binary '@/home/user/Pictures/photo.png'

获取图片下载地址

curl --location --request GET 'http://localhost:4001/profiles/[id]/image/download'

包起来

在这次探索中,我们使用 Nitric 创建了一个配置文件管理 API,处理核心配置文件操作,并将其扩展为图像管理。

事实证明,Nitric 是快速从想法转变为实时云托管 API 的可靠伴侣。现在轮到您扩展这个项目或与 Nitric 一起开始新的冒险了。

查看具体文档:(https://nitric.io/docs/guides/getting-started/go/serverless-rest-api-example)

文章来源地址 https://www.toymoban.com/diary/golang/351.html

到此这篇关于如何使用 GO 和 Nitric 创建您的第一个 API | Nitric 和 GO 教程的文章就介绍到这了, 更多相关内容可以在右上角搜索或继续浏览下面的相关文章,希望大家以后多多支持 TOY 模板网!

    正文完
     0
    Yojack
    版权声明:本篇文章由 Yojack 于1970-01-01发表,共计7352字。
    转载说明:
    1 本网站名称:优杰开发笔记
    2 本站永久网址:https://yojack.cn
    3 本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长进行删除处理。
    4 本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
    5 本站所有内容均可转载及分享, 但请注明出处
    6 我们始终尊重原创作者的版权,所有文章在发布时,均尽可能注明出处与作者。
    7 站长邮箱:laylwenl@gmail.com
    评论(没有评论)