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!

Golangisidealforperformance-criticalapplicationsandconcurrentprogramming,whilePythonexcelsindatascience,rapidprototyping,andversatility.1)Forhigh-performanceneeds,chooseGolangduetoitsefficiencyandconcurrencyfeatures.2)Fordata-drivenprojects,Pythonisp

Golang achieves efficient concurrency through goroutine and channel: 1.goroutine is a lightweight thread, started with the go keyword; 2.channel is used for secure communication between goroutines to avoid race conditions; 3. The usage example shows basic and advanced usage; 4. Common errors include deadlocks and data competition, which can be detected by gorun-race; 5. Performance optimization suggests reducing the use of channel, reasonably setting the number of goroutines, and using sync.Pool to manage memory.

Golang is more suitable for system programming and high concurrency applications, while Python is more suitable for data science and rapid development. 1) Golang is developed by Google, statically typing, emphasizing simplicity and efficiency, and is suitable for high concurrency scenarios. 2) Python is created by Guidovan Rossum, dynamically typed, concise syntax, wide application, suitable for beginners and data processing.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Go language has unique advantages in concurrent programming, performance, learning curve, etc.: 1. Concurrent programming is realized through goroutine and channel, which is lightweight and efficient. 2. The compilation speed is fast and the operation performance is close to that of C language. 3. The grammar is concise, the learning curve is smooth, and the ecosystem is rich.

The main differences between Golang and Python are concurrency models, type systems, performance and execution speed. 1. Golang uses the CSP model, which is suitable for high concurrent tasks; Python relies on multi-threading and GIL, which is suitable for I/O-intensive tasks. 2. Golang is a static type, and Python is a dynamic type. 3. Golang compiled language execution speed is fast, and Python interpreted language development is fast.

Golang is usually slower than C, but Golang has more advantages in concurrent programming and development efficiency: 1) Golang's garbage collection and concurrency model makes it perform well in high concurrency scenarios; 2) C obtains higher performance through manual memory management and hardware optimization, but has higher development complexity.

Golang is widely used in cloud computing and DevOps, and its advantages lie in simplicity, efficiency and concurrent programming capabilities. 1) In cloud computing, Golang efficiently handles concurrent requests through goroutine and channel mechanisms. 2) In DevOps, Golang's fast compilation and cross-platform features make it the first choice for automation tools.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor