HTTP Server Swagger Auth
Description
This example demonstrates how to implement Basic Authentication for Swagger API documentation using GoFrame framework. The example shows how to:
- Set up a basic HTTP server with OpenAPI/Swagger documentation
- Protect the Swagger documentation with Basic Authentication
- Define and implement a simple REST API endpoint
Requirements
Structure
.
├── README.MD # English documentation
├── README.ZH.MD # Chinese documentation
├── go.mod # Go module file
└── main.go # Main application entry pointFeatures
- OpenAPI/Swagger documentation integration
- Basic Authentication protection for API documentation
- RESTful API endpoint implementation
- Request/Response validation
- API documentation comments
Setup
Clone the repository:
git clone https://github.com/gogf/examples.git cd examples/httpserver/swagger-authInstall the dependencies:
go mod tidyRun the application:
go run main.go
Usage
Start the server:
go run main.goAccess the protected Swagger documentation:
- URL: http://localhost:8000/swagger
- Basic Auth Credentials:
- Username: admin
- Password: 123456
Test the API endpoint:
- Access: http://localhost:8000/hello?name=GoFrame
- Method: GET
- Response: JSON containing greeting message
Implementation Details
The example demonstrates several key features:
Swagger Integration:
- OpenAPI JSON at
/api.json - Swagger UI at
/swagger - Both protected by Basic Authentication
- OpenAPI JSON at
Basic Authentication:
- Username: admin
- Password: 123456
- Realm: "Restricted"
API Endpoint:
- Path:
/hello - Method: GET
- Required Parameter: name
- Response: JSON with greeting message
- Path:
Notes
- The Basic Authentication is implemented using GoFrame's built-in
BasicAuthmethod - API documentation is automatically generated from code comments and struct tags
- The server runs on port 8000 by default
- All API responses are automatically wrapped in a standard format using middleware