头图

How does the back end provide the API at work? swaggo is very good

Last time we briefly shared the Casbin of GO permission management, he generally refers to according to the security rules or security policies set by the system

  • Shared what rights management is
  • What is Casbin
  • Features of Casbin
  • Casbin application case

If interested, you can after a lot of in-depth discussion and sharing, welcome to view the article GO Casbin rights management of

Today, let’s share with us how our back-end partners can efficiently provide API

API is composed of a set of definitions and protocols, which can be used to build and integrate enterprise application software

API is application programming interface

I believe that many friends who like to write documents may use markdown to write down the interface, and the relevant person in charge has agreed on a fixed template

Some will use simple text files, and some big brothers may not even output any documents, so that they will not survive the second episode of

What about when testing?

Generally, the postman tool is used to set parameters against the interface, perform self-test, or write scripts for testing

However, this is too cumbersome, and it takes too much time to draw on the writing interface. Every time you modify the interface, you must modify the corresponding document, which is quite cumbersome and a bit anti-human.

Let's take a look at how the GO swaggo tool solves the above problems, and what are the operations?

What is swaggo?

It is a tool specially used to automatically convert golang Swagger 2.0 documents

What is Swagger?

Swagger is a web service

It is a standardized and complete framework that can generate, describe, call and visualize RESTful style documents

So what is his advantage?

There are roughly the following 2 advantages:

  • Support API to automatically generate synchronized online documents

After using Swagger , you can directly generate documentation through code, and you no longer need to manually write interface documentation by yourself

  • Provide Web page online test API

The documents generated by Swagger

The parameters and format are all set, you can directly enter the corresponding value of the parameter on the interface to test the interface online.

How do we use swaggo?

Let's write a basic swaggo , roughly divided into the following steps:

  • Install swag for automatic document generation
  go get -u github.com/swaggo/swag/cmd/swag
  • You need to use the following two packages, you can know in advance, we still use go mod by default. After writing the code, go directly to build, and all the packages used will be pulled down.

The first one is gin-swagger . It is more convenient for us to use gin to play swagger. I have also shared gin are interested, you can check the article Gin actual combat exercise

go get github.com/swaggo/gin-swagger

The second is the swagger built-in file

go get github.com/swaggo/gin-swagger/swaggerFiles
  • Need to simply use the gin framework

Let's start coding a simple small DEMO

package main

import (
   "github.com/gin-gonic/gin"
   ginSwagger "github.com/swaggo/gin-swagger"
   "github.com/swaggo/gin-swagger/swaggerFiles"
   "net/http"
   _ "myswa/docs"
)

// gin 的处理函数  Hello
func Hello(c *gin.Context) {

   c.JSON(http.StatusOK, gin.H{"msg": "hello wrold xiaomotong" })
}

func main() {

   r := gin.Default()

   r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

   // 路由分组, 第一个版本的api  v1
   v1 := r.Group("/api/v1")
   {
      v1.GET("/hello", Hello)

   }

   // 监听端口为 8888
   r.Run(":8888")
}

The above code is roughly divided into these steps:

  • Use r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) to register swaggerFiles.Handler
  • Write a custom route and corresponding method
  • Listen to the specified address and port

After the above code is written, we can main.go in the same directory as go , and then we run the program at go build

go mod init myswa
go build

The above command go mod init myswa , the initialization module is myswa , and the path to import our local packages in the future start

After executing the above command, a myswa will be initialized. After executing go build , the related packages used will be pulled down and compiled

After the compilation is successful, type in the browser:

http://127.0.0.1:8888/swagger/index.html

If the view to print the following error message, because there is no installation swag of docs

Here you can check whether the swap installation is successful

go get -u github.com/swaggo/swag/cmd/swag

After the installation is successful, you can use swag init to initialize, swag will help us generate the corresponding docs , for example, my code directory looks like this

This is why one of the packages we imported is _ "myswa/docs"

Type in the browser again:

http://127.0.0.1:8888/swagger/index.html , you can see the following effect, it is successful

add notes

Let's main.go file, and then take a look at the effect, for example

package main

import (
    "github.com/gin-gonic/gin"
    ginSwagger "github.com/swaggo/gin-swagger"
    "github.com/swaggo/gin-swagger/swaggerFiles"
    "net/http"
    _ "myswa/docs"
)

// gin 的处理函数  Hello
func Hello(c *gin.Context) {

    c.JSON(http.StatusOK, gin.H{"msg": "hello wrold xiaomotong" })
}
// @title Xiaomotong Swagger  API
// @version 1.0
// @description 参加更文挑战第 26 天了,主题是 Swagger
// @termsOfService https://juejin.cn/user/3465271329953806

// @contact.name https://juejin.cn/user/3465271329953806
// @contact.url https://juejin.cn/user/3465271329953806
// @contact.email xxx@xxx.com.cn


// @host 127.0.0.1:8888
// @BasePath /api/v1
func main() {

    r := gin.Default()

    r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

    // 路由分组, 第一个版本的api  v1
    v1 := r.Group("/api/v1")
    {
        v1.GET("/hello", Hello)

    }

    // 监听端口为 8888
    r.Run(":8888")
}

After adding comments, perform the following 3 :

  • Delete the previously generated docs directory
  • Again main.go perform at the same level directory swag init generate new documents
  • Execution go run main.go , browser access http://127.0.0.1:8888/swagger/index.html we can see the following results

Check the docs directory we generated at this time to see what the specific file contents are?

These are all automatically generated

my_swa/docs/swagger.json as follows

{
    "swagger": "2.0",
    "info": {
        "description": "参加更文挑战第 26 天了,主题是 Swagger",
        "title": "Xiaomotong Swagger  API",
        "termsOfService": "https://juejin.cn/user/3465271329953806",
        "contact": {
            "name": "https://juejin.cn/user/3465271329953806",
            "url": "https://juejin.cn/user/3465271329953806",
            "email": "xxx@xxx.com.cn"
        },
        "version": "1.0"
    },
    "host": "127.0.0.1:8888",
    "basePath": "/api/v1",
    "paths": {}
}

my_swa/docs/swagger.yaml as follows:

basePath: /api/v1
host: 127.0.0.1:8888
info:
  contact:
    email: xxx@xxx.com.cn
    name: https://juejin.cn/user/3465271329953806
    url: https://juejin.cn/user/3465271329953806
  description: 参加更文挑战第 26 天了,主题是 Swagger
  termsOfService: https://juejin.cn/user/3465271329953806
  title: Xiaomotong Swagger  API
  version: "1.0"
paths: {}
swagger: "2.0"

The actual UI displayed by 0611723afc144e comes from the above two files

For the keywords in the above comments, let's make a table and take a look

taginstruction
titileDocument title
versionVersion
descriptionDescription, can be written or not
hostService document port
BasePathBase path
SummarySummarize
Descriptiondescribe
TagsUsed to group APIs
AcceptThe received parameter type, supports form ( mpfd ) and JSON ( json )
ParamParameters, specific wording as follows:
@Param parameter name Parameter Type Data Type Must Parameter Description Attributes
type parameter
- path value of this type can be spliced directly to the URL of the top
@ param name path string true "specific name" - query this type and URL value is generally combined

- query this type and URL value is generally combined
@Param name Query String to true "specific name"

- formData this type The value of is generally used in the POST method or the PUT method
@Param name formData string true "specific name" default(root)

The data types of the parameters are as follows:
string(string), integer (int, uint, uint32, uint64), number (float32 ), boolean (bool), file for uploading files

other attributes support **:
- enumeration
- value added range
- set defaults
SuccessWhat to do if the response is successful
@Success HTTP response code {response parameter type} response data type Other description
FailureWhat to do if the response fails
@Failure HTTP response code {response parameter type} response data type Other description
Router
without base path @Router /hello [get]

Let's add corresponding comments to the function to see the effect

// @Summary hello world
// @Description 对谁说 hello wrold
// @Tags 挑战测试
// @Accept json
// @Param name query string true "具体名字"
// @Success 200 {string} string "{"msg": "hello xxx"}"
// @Failure 400 {string} string "{"msg": "NO name"}"
// @Router /hello [get]
// gin 的处理函数  Hello
func Hello(c *gin.Context) {
   name := c.Query("name")
   c.JSON(http.StatusOK, gin.H{"msg": "hello wrold" + name})
}

After adding comments, perform the following 3 :

  • Delete the previously generated docs directory
  • main.go same directory as swag init generate the latest document
  • Execution go run main.go , browser access http://127.0.0.1:8888/swagger/index.html we can see the following results

Let's do a basic test on the page, fill in the name, execute it, and see the effect

Now, the test is successful

If such a document is given, it will be very friendly to the front end, and it will not increase our workload. When writing the code, write the comments by the way

release

After the development is completed, when the version is released, it is impossible to bring your own api document, it should not be

Therefore, we can build tag . Here is a suspense, and interested friends can try it

Interested friends, you can paste the above code locally, install the corresponding library, execute it, and see the effect, it is really easy to use, I hope it can help you

Summarize

  • What is swaggo
  • What is swagger
  • How to use swapgo
  • How to test swapgo

Welcome to like, follow, favorite

Friends, your support and encouragement are my motivation to keep sharing and improve quality

Okay, that’s it for this time, next GO timer and timing task cron

Technology is open, and our mindset should be more open. Embrace the change, live toward the sun, and work hard to move forward.

I little devil child Rebels , welcome thumbs concern the collection, see you next time ~


阿兵云原生
192 声望37 粉丝