您的位置 首页 golang

使用Beego + Swagger构建API

(原文作者:Arnesh Agrawal)

使用Beego + Swagger构建API

Markus Spiske在Unsplash上拍摄的照片

为什么是Beego?

Beego是一个RESTful HTTP框架,用于在Golang中开发Web应用程序和API,并遵循Model-View-Controller(MVC)体系结构。它支持用Swagger来自动生成文档,这使我们的工作更加轻松。

在本文中,我将讨论Beego框架的基础知识以及Swagger如何在文档中为我们提供帮助。

先决条件

  • 进入设置(遵循此)
  • Beego安装(遵循此)

让我们开始吧

假设您已经成功设置了Go and Beego,就该开始了!
首先,我希望您在终端中运行一个简单的命令。

 bee  

这应该输出类似:

使用Beego + Swagger构建API

如果您的输出与此匹配,则表明您已成功设置了此项目所需的所有内容。如果不是,请继续解决该问题。

让我们为本教程创建一个新的API,将其命名为test_api

 bee api test_api  

该命令将创建一个目录“ test_api”,其中包含以下文件夹和文件:

 -conf
-controllers
-main.go
-models
-routers
-tests  

简而言之,路由器是指定端点的地方(,控制器是API的大脑,模型是用于控制器所需的数据处理的地方,而conf是用于存储凭据和有关API的其他信息的配置文件。

默认情况下,我们已经在routers目录的router.go文件中创建了“用户”和“对象”端点。

 func init() {
	ns := beego.NewNamespace("/v1",
		beego.NSNamespace("/object",
			beego.NSInclude(
				&controllers.ObjectController{},
			),
		),
		beego.NSNamespace("/user",
			beego.NSInclude(
				&controllers.UserController{},
			),
		),
                beego.NSNamespace("/test",
			beego.NSInclude(
				&controllers.TestController{},
			),
		),
	)
	beego.AddNamespace(ns)
}  

(

此代码段指定端点 v1/object 由处理 ObjectController 。我已经 test 按照本教程的类似规范创建了一个端点。现在,我们可以在这里忽略所有其他关键字,而只关注端点和处理端点的控制器。
每当对 v1/test 端点执行调用时,都会执行内部的逻辑 TestController

现在,我们需要制作两个新文件:控制器中的test.go和模型中的test.go。
控制器中的test.go基本上是 TestController ,模型的文件是此特定控制器的模型。

 package controllers

import (
	"test_api/models"
	"github.com/astaxie/beego"

)

type TestController struct {
	beego.Controller
}

// @Title TestEndpoint
// @Description Tests the API
// @Success 200 {object} models.Test
// @Failure 403 body is empty
// @router /hello [get]
func (t *TestController) Test() {
	Response := models.TestFunction()
	t.Data["json"] = Response
	t.ServeJSON()  
}  

(

每个控制器的布局都是相同的,因此我们实际上可以在此处使用用户控制器的代码,并根据需要对其进行修改。关于函数 Test() ,只要执行此函数, Response 变量就会 TestFunction 在模型中调用该函数并存储接收到的数据。然后,控制器将数据编码为JSON形式并返回。

这很简单
但是在这里更重要的是要理解之前的评论 TestFunction
这些注释实际上在API和文档中起作用。
这些评论 @Title @Description 是自描述它们的功能和使用是对文件的。
@Success 并分别 @Failure 指示对端点执行成功和失败的响应。这些注释后的整数表示响应代码,这些整数后的值表示返回类型。这些注释也用于文档。
最后一条评论 @Router 暗示了端点将是什么及其功能。 /hello @Router 是在router.go中指定的初始端点之外的功能,即在 Test 需要端点时执行该功能 v1/test/hello [get] 表示HTTP请求是GET请求。在此处
了解有关HTTP请求的更多信息。可以得到有关在Beego框架这样的评论的详细解释在这里。

进入模型的代码:

 package models

import (
	
)

type Test struct {
	Response string 
}

func TestFunction() Test {
	 var test_var Test 
	 test_var.Response = "Hello World"
	 return test_var
}  

(

功能 TestFunction ,具有返回类型结构 Test ,是由控制器调用。它为该结构创建一个新变量,分配 Response 为“ Hello World”并返回该结构。
所有数据处理和修改都应在此处执行。

恭喜你 !我们已经完成了本教程的API编码。现在是时候测试我们的API并生成一些文档了。

 bee run  

在目录中使用此命令 test_api 来运行我们的本地服务器以测试我们的端点。现在,打开浏览器并输入:

   

输出应为:

 {
  "Response": "Hello World"
}  
使用Beego + Swagger构建API

终端运行我们的本地服务器

现在开始自动生成文档,结束服务器的会话并使用以下命令:

 bee run -gendoc=true -downdoc=true  

现在,转到浏览器并输入:

   

这是我们API的自动生成的文档。我们可以查看端点的文档。

使用Beego + Swagger构建API

测试端点(endpoint)的文档

瞧!本教程到此结束。我希望您从中学到了一些有价值的东西。我在下面发布了一些重要链接,以帮助您更好地开发Beego。

链接

  • (要学习Golang的基础知识)
  • (Beego文档)
  • (Golang文档)
  • (开发API的良好做法)

PS-除非另有说明,否则我要求拥有本博客文章中使用的所有图片和代码段的所有权利。

谢谢你!

原文地址:

文章来源:智云一二三科技

文章标题:使用Beego + Swagger构建API

文章地址:https://www.zhihuclub.com/98653.shtml

关于作者: 智云科技

热门文章

评论已关闭

38条评论

  1. The results produced by this medicine were estimated during several great studies I cannot remember today if I got this order personally

  2. If you have a desire to spend a romantic night with your girlfriend, then you should know that applying such a drug, you will be satisfied with the outcome Been two days off the pill, and wake up with a glorious case of morning wood still

  3. Additionally, male athletes may misuse aromatase inhibitors like letrozole in order to increase their own natural testosterone levels by blocking the breakdown of testosterone.

  4. Whether acute disseminated Borrelia burgdorferi infection should be treated differently from localized infection is unknown. Previous studies showed that hepatocytes are sensitive to flow sorting 35; therefore, we optimized a hepatocyte isolation protocol without flow cytometry to harvest the greatest number of viable hepatocytes for sequencing.

  5. Magnesium responsible for hundreds of enzyme responses that impact natural hormone balance

  6. The draft recommendation noted that aromatase inhibitors do not reduce, and may even increase, the risk of fractures

  7. This isn t a simple or easy lesson for a man to learn, but it s essential to reclaiming and renewing sexuality post surgery

  8. Couldn t stand it If CG 5 cells are pretreated with different concentrations of IFN and subsequently exposed to 10

  9. The authors present a case of breast cancer metastasizing to the calcaneus that was confirmed by bone biopsy

  10. To investigate whether acupuncture might be an option, Walker and her team randomly assigned 25 women to receive Effexor or acupuncture for 12 weeks, following them for up to year after the end of treatment Am J Manag Care

  11. Anastrozole tablets 1 mg N 262 n Anastrozole tablets 10 mg N 246 n Megestrol Acetate 160 mg N 253 n Asthenia 42 16 33 13 47 19 Nausea 41 16 48 20 28 11 Headache 34 13 44 18 24 9 Hot Flashes 32 12 29 11 21 8 Pain 28 11 38 15 29 11 Back Pain 28 11 26 11 19 8 Dyspnea 24 9 27 11 53 21 Vomiting 24 9 26 11 16 6 Cough Increased 22 8 18 7 19 8 Diarrhea 22 8 18 7 7 3 Constipation 18 7 18 7 21 8 Abdominal Pain 18 7 14 6 18 7 Anorexia 18 7 19 8 11 4 Bone Pain 17 6 26 12 19 8 Pharyngitis 16 6 23 9 15 6 Dizziness 16 6 12 5 15 6 Rash 15 6 15 6 19 8 Dry Mouth 15 6 11 4 13 5 Peripheral Edema 14 5 21 9 28 11 Pelvic Pain 14 5 17 7 13 5 Depression 14 5 6 2 5 2 Chest Pain 13 5 18 7 13 5 Paresthesia 12 5 15 6 9 4 Vaginal Hemorrhage 6 2 4 2 13 5 Weight Gain 4 2 9 4 30 12 Sweating 4 2 3 1 16 6 Increased Appetite 0 0 1 0 13 5

  12. Even if you can eat a hundred eggs in one bite, you cannot quickly convert these eggs into Twenty amino acids needed Two cores were evaluated from each tumor and only staining of the invasive malignant cells was considered

  13. Aiyer 3 6 727 37 Atalay et al Anti angiogenic property of edible berry in a model of hemangioma Hopefully current shelf exams keep their intentions as clear

  14. Serious Use Alternative 2 phenytoin will decrease the level or effect of letermovir by Other see comment You do not need a sleeping bag if the size of your bag is any consideration to you; there are always blankets or bags for hire if needed

  15. Basil, USA 2022 06 28 09 48 15 Oxidative stress noticed after TAM intoxication was associated with decreased hepatic GSH concomitant with increased peroxidation Oge et al

  16. As I was saying in a recent article instead of stocking up 10 types of antibiotics many having similar substances you should consider 4 5 with totally different actions, so if the bacteria is resistant to one of them, you have 4 totally different solutions to try ketotifen viagra tablet how to use in kannada Deutsche had appeared to condone collaboration betweendifferent parts of the trading desk when it imported toFrankfurt a short term interest rate trading seatingarrangement used in Asia, whereby money market traders, swapstraders and derivative traders sat in close proximity

  17. Already effective against breast cancer, the drug Tamoxifen has secondary effects that can turbo charge white blood cells, giving them extra power to chase down, trap and consume antibiotic resistant bacteria Ebstein anomaly may be diagnosed at birth and during early childhood

  18. They are really busy, and you see different nurses, which can be annoying ZasДЌiurinskienД—, E

  19. 16 However, whereas salt restriction increases diuretic induced negative salt balance, 13 it also increases renin, Ang II angiotensin II, aldosterone, and renal K losses 17, 18 and may increase the risk of death in patients with HF

  20. Taking caffeine over a long time period along with tiagabine can increase the amount of tiagabine in the body 1989; 60 262 264

  21. com 20 20Orjinal 20Viagra orjinal viagra The Minister of National Languages and Social Integration told the High Commissioner that he has proposed new legislation on hate speech

  22. vepesid augmentin duo 1gm dosage House Republican leaders acted to break a logjam in talks byproposing a bill to raise the government s debt limit withoutattachments, a significant move as the Oct

网站地图