Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/long2ice/swagin
Swagger + Gin = SwaGin, a web framework based on Gin and Swagger
https://github.com/long2ice/swagin
api fastapi gin golang openapi redoc swagger swagger-ui
Last synced: 7 days ago
JSON representation
Swagger + Gin = SwaGin, a web framework based on Gin and Swagger
- Host: GitHub
- URL: https://github.com/long2ice/swagin
- Owner: long2ice
- License: apache-2.0
- Created: 2021-08-10T14:54:54.000Z (over 3 years ago)
- Default Branch: dev
- Last Pushed: 2023-06-20T09:33:44.000Z (over 1 year ago)
- Last Synced: 2025-01-20T12:02:43.095Z (13 days ago)
- Topics: api, fastapi, gin, golang, openapi, redoc, swagger, swagger-ui
- Language: Go
- Homepage: https://swagin.long2ice.io/docs
- Size: 481 KB
- Stars: 72
- Watchers: 4
- Forks: 18
- Open Issues: 4
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
- Security: security/apikey.go
Awesome Lists containing this project
README
# Swagger + Gin = SwaGin
[![deploy](https://github.com/long2ice/swagin/actions/workflows/deploy.yml/badge.svg)](https://github.com/long2ice/swagin/actions/workflows/deploy.yml)
[![Go Reference](https://pkg.go.dev/badge/github.com/long2ice/swagin.svg)](https://pkg.go.dev/github.com/long2ice/swagin)**If you use [Fiber](https://github.com/gofiber/fiber), you can try my another similar
project [Fibers](https://github.com/long2ice/fibers).**## Introduction
`SwaGin` is a web framework based on `Gin` and `Swagger`, which wraps `Gin` and provides built-in swagger api docs and
request model validation.## Why I build this project?
Previous I have used [FastAPI](https://github.com/tiangolo/fastapi), which gives me a great experience in api docs
generation, because nobody like writing api docs.Now I use `Gin` but I can't found anything like that, I found [swag](https://github.com/swaggo/swag) but which write
docs with comment is so stupid. So there is `SwaGin`.## Installation
```shell
go get -u github.com/long2ice/swagin
```## Online Demo
You can see online demo at or .
![](https://raw.githubusercontent.com/long2ice/swagin/dev/images/docs.png)
![](https://raw.githubusercontent.com/long2ice/swagin/dev/images/redoc.png)And you can reference all usage in [examples](https://github.com/long2ice/swagin/tree/dev/examples).
## Usage
### Build Swagger
Firstly, build a swagger object with basic information.
```go
package examplesimport (
"github.com/getkin/kin-openapi/openapi3"
"github.com/long2ice/swagin/swagger"
)func NewSwagger() *swagger.Swagger {
return swagger.New("SwaGin", "Swagger + Gin = SwaGin", "0.1.0",
swagger.License(&openapi3.License{
Name: "Apache License 2.0",
URL: "https://github.com/long2ice/swagin/blob/dev/LICENSE",
}),
swagger.Contact(&openapi3.Contact{
Name: "long2ice",
URL: "https://github.com/long2ice",
Email: "[email protected]",
}),
swagger.TermsOfService("https://github.com/long2ice"),
)
}
```### Write API
Then write a router function.
```go
package examplestype TestQuery struct {
Name string `query:"name" validate:"required" json:"name" description:"name of model" default:"test"`
}func TestQuery(c *gin.Context, req TestQueryReq) error {
return c.JSON(req)
}// TestQueryNoReq if there is no req body and query
func TestQueryNoReq(c *gin.Context) {
c.JSON(http.StatusOK, "{}")
}
```Note that the attributes in `TestQuery`? `SwaGin` will validate request and inject it automatically, then you can use it
in handler easily.### Write Router
Then write router with some docs configuration and api.
```go
package examplesvar query = router.New(
TestQuery,
router.Summary("Test Query"),
router.Description("Test Query Model"),
router.Tags("Test"),
)// if there is no req body, you need use router.NewX
var query = router.NewX(
TestQueryNoReq,
router.Summary("Test Query"),
router.Description("Test Query Model"),
router.Tags("Test"),
)
```### Security
If you want to project your api with a security policy, you can use security, also they will be shown in swagger docs.
Current there is five kinds of security policies.
- `Basic`
- `Bearer`
- `ApiKey`
- `OpenID`
- `OAuth2````go
package mainvar query = router.New(
TestQuery,
router.Summary("Test query"),
router.Description("Test query model"),
router.Security(&security.Basic{}),
)
```Then you can get the authentication string by `context.MustGet(security.Credentials)` depending on your auth type.
```go
package mainfunc TestQuery(c *gin.Context) {
user := c.MustGet(security.Credentials).(*security.User)
fmt.Println(user)
c.JSON(http.StatusOK, t)
}
```### Mount Router
Then you can mount router in your application or group.
```go
package mainfunc main() {
app := swagin.New(NewSwagger())
queryGroup := app.Group("/query", swagin.Tags("Query"))
queryGroup.GET("", query)
queryGroup.GET("/:id", queryPath)
queryGroup.DELETE("", query)
app.GET("/noModel", noModel)
}```
### Start APP
Finally, start the application with routes defined.
```go
package mainimport (
"github.com/gin-contrib/cors"
"github.com/long2ice/swagin"
)func main() {
app := swagin.New(NewSwagger())
app.Use(cors.New(cors.Config{
AllowOrigins: []string{"*"},
AllowMethods: []string{"*"},
AllowHeaders: []string{"*"},
AllowCredentials: true,
}))queryGroup := app.Group("/query", swagin.Tags("Query"))
queryGroup.GET("", query)
queryGroup.GET("/:id", queryPath)
queryGroup.DELETE("", query)formGroup := app.Group("/form", swagin.Tags("Form"))
formGroup.POST("/encoded", formEncode)
formGroup.PUT("", body)app.GET("/noModel", noModel)
app.POST("/body", body)
if err := app.Run(); err != nil {
panic(err)
}
}
```That's all! Now you can visit or to see the api docs. Have
fun!### Disable Docs
In some cases you may want to disable docs such as in production, just put `nil` to `swagin.New`.
```go
app = swagin.New(nil)
```### SubAPP Mount
If you want to use sub application, you can mount another `SwaGin` instance to main application, and their swagger docs
is also separate.```go
package mainfunc main() {
app := swagin.New(NewSwagger())
subApp := swagin.New(NewSwagger())
subApp.GET("/noModel", noModel)
app.Mount("/sub", subApp)
}```
## Integration Tests
First install Venom at . Then you can run integration tests as follows:
```
$ cd examples
$ go test
```This will start example application and run integration tests in directory *examples/test* against it.
You can also run integration tests on running example application with:
```
$ cd examples
$ go build
$ ./examples &
$ PID=$!
$ venom run test/*.yml
$ kill $PID
```## ThanksTo
- [kin-openapi](https://github.com/getkin/kin-openapi), OpenAPI 3.0 implementation for Go (parsing, converting,
validation, and more).
- [Gin](https://github.com/gin-gonic/gin), an HTTP web framework written in Go (Golang).## License
This project is licensed under the
[Apache-2.0](https://github.com/long2ice/swagin/blob/master/LICENSE)
License.