Using SwaggerUI in Golang for API online documentation automation
Using SwaggerUI for API online documentation automation in Golang
The use of APIs (Application Programming Interfaces) has become a necessary element in modern application development. API makes front-end and back-end separation, microservices and cloud applications easier. However, a good API does not just implement functionality, but is user-friendly and easy to use. For this reason, documented APIs are becoming increasingly important. The benefit of online documentation is that you can learn about the API before operating it.
In this article, we will introduce how to use SwaggerUI to record API documentation and how to automate this process in Golang so that it is easier to maintain and provide readable documentation so that other teams and partners can understand you. API.
SwaggerUI is a popular tool for creating documentation for APIs, generating interactive API documentation, describing the API in a visual way, and can generate both human-readable documentation and machine-readable JSON or YAML. SwaggerUI integrates with many programming languages, including Golang.
First, you need to use the Golang implementation of SwaggerUI - Swag. Swag is an automated API documentation tool that combines Go language annotations and Swagger annotations to automatically generate Swagger 2.0 documents.
Step 1: Install Swag
Download and install Swag using the following commands in terminal/cmd:
go get -u github.com/swaggo/swag/cmd/swag
Step 2: Add Swagger annotations in the code
Add Swagger comments to the code to describe the API.
Add Swagger annotation in the comment above the HTTP handler function, for example:
// GetByID godoc // @Summary Get user details by ID // @Description Get user details by ID // @Tags user // @Accept json // @Produce json // @Param id path int true "User ID" // @Success 200 {object} model.User // @Failure 400 {object} ErrorResponse // @Router /users/{id} [get] func GetByID(c *gin.Context) { //…code here… }
Step 3: Generate Swagger JSON file
Use the following command in the root directory of the code base Generate Swagger JSON file in:
swag init
This command will use the Swagger annotation in the code and generate a Swagger JSON file. You can also add it in your project's Makefile.
Step 4: Integrate SwaggerUI
Swag uses SwaggerUI as the front end for displaying API documents in the browser. We need to statically reverse proxy the files in SwaggerUI to our application.
Assume our Golang application is running on port 8080. The version of SwaggerUI we will be using is v3.31.1. We can download it from the official SwaggerUI GitHub page by:
curl -L https://github.com/swagger-api/swagger-ui/archive/v3.31.1.tar.gz -o swagger-ui.tar.gz tar -xf swagger-ui.tar.gz
This will generate the swagger-ui folder in the local directory, which contains all the files of SwaggerUI. We will use nginx as a reverse proxy server (you can use Apache, Caddy, etc.), start nginx with the following command in terminal/cmd:
nginx -c /path/to/nginx.conf
In the nginx.conf file, we need to add the following:
http { server { listen 8081; # 访问静态文件的端口 server_name _; root /path/to/swagger-ui/dist; location / { try_files $uri $uri/ @go; } location @go { proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://127.0.0.1:8080; # 代理请求的端口 } location /swagger-ui/ { try_files $uri $uri/ =404; } } }
In the above nginx configuration, we add the static SwaggerUI folder /swagger-ui/dist directory to the root directory of the nginx server as static files, and we proxy to localhost:8080 (our own application ) are forwarded to the port listened by port 8081. We view and use SwaggerUI by visiting http://localhost:8081/swagger-ui/.
Step 5: View the API documentation
Visit http://localhost:8081/swagger-ui/ in the browser, the SwaggerUI application will display the SwaggerUI static files that appear in the root directory folder. You can find a list of all well-documented APIs on this page. Click on the API documentation you want to view to be displayed on the right. The website provides an API user-friendly interface for testing and viewing API documentation directly on the API. During this process, the GUI displays the detailed information automatically extracted by Swagger annotations, such as providing the parameters of this API, body information, API version, API format, etc. This will greatly save you time and energy in writing documents.
Conclusion
API documentation is an important tool in the API design and development process, so we need to consider documented APIs when building applications. Using the automation tool Swag, we can easily automate API documentation in Golang. It is also very convenient to use SwaggerUI as a visualization tool to view and test documented APIs. This will help other teams and collaboration partners and make it easier for them to understand our API.
The above is the detailed content of Using SwaggerUI in Golang for API online documentation automation. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

How to configure connection pooling for Go database connections? Use the DB type in the database/sql package to create a database connection; set MaxOpenConns to control the maximum number of concurrent connections; set MaxIdleConns to set the maximum number of idle connections; set ConnMaxLifetime to control the maximum life cycle of the connection.

The Go framework stands out due to its high performance and concurrency advantages, but it also has some disadvantages, such as being relatively new, having a small developer ecosystem, and lacking some features. Additionally, rapid changes and learning curves can vary from framework to framework. The Gin framework is a popular choice for building RESTful APIs due to its efficient routing, built-in JSON support, and powerful error handling.

The difference between the GoLang framework and the Go framework is reflected in the internal architecture and external features. The GoLang framework is based on the Go standard library and extends its functionality, while the Go framework consists of independent libraries to achieve specific purposes. The GoLang framework is more flexible and the Go framework is easier to use. The GoLang framework has a slight advantage in performance, and the Go framework is more scalable. Case: gin-gonic (Go framework) is used to build REST API, while Echo (GoLang framework) is used to build web applications.

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

Best practices: Create custom errors using well-defined error types (errors package) Provide more details Log errors appropriately Propagate errors correctly and avoid hiding or suppressing Wrap errors as needed to add context

How to address common security issues in the Go framework With the widespread adoption of the Go framework in web development, ensuring its security is crucial. The following is a practical guide to solving common security problems, with sample code: 1. SQL Injection Use prepared statements or parameterized queries to prevent SQL injection attacks. For example: constquery="SELECT*FROMusersWHEREusername=?"stmt,err:=db.Prepare(query)iferr!=nil{//Handleerror}err=stmt.QueryR

The FindStringSubmatch function finds the first substring matched by a regular expression: the function returns a slice containing the matching substring, with the first element being the entire matched string and subsequent elements being individual substrings. Code example: regexp.FindStringSubmatch(text,pattern) returns a slice of matching substrings. Practical case: It can be used to match the domain name in the email address, for example: email:="user@example.com", pattern:=@([^\s]+)$ to get the domain name match[1].
