Steps
Install
go get -u github.com/swaggo/swag/cmd/swag
go get -u github.com/swaggo/http-swagger/v2
go get -u github.com/alecthomas/template
Bash
복사
Application | Description |
swag | Swagger 2.0의 Go annotations 활용 |
http-swagger | Swagger UI를 doc으로 만들어 줌 |
templete | UI 탬플릿 |
Definition
import (
_ "{Project_Name}/docs"
httpSwagger "github.com/swaggo/http-swagger"
)
// @title
// @version
// @description
// @host localhost:9999
// @BasePath /
func main() {
router := mux.NewRouter()
router.PathPrefix("/swagger").Handler(httpSwagger.WrapHandler)
http.ListenAndServe(":9999", router)
}
Go
복사
Create Docs (Swagger v2)
swag init
또는
swag init -g {annotation 대상 route 파일, 통상적으로는 main.go}
~/go/bin/swag
Bash
복사
Open Docs
http://localhost/swagger/index.html
Plain Text
복사
Swagger v3 (OpenAPI)
Reference
Convert v2 into v3
curl -X POST https://converter.swagger.io/convert -d @docs/swagger.json --header 'Content-Type: application/json' > openapi.json
Bash
복사
Or, convert locally using docker from swagger-converter
Replacing
We will have to replace v2 into v3 in the docs.go file.
To save all the trouble, here is a magical command that does that:
sed -i '/var doc = `{/,/}`/c\var doc = `'"$(cat openapi.json)"'`' docs/docs.go
Bash
복사
This will replace doc variable value with the content from openapi.json file.
Building
Now, the last thing that is left is to run go build to regenerate the binaries and we will be able to access v3 documentation from our service, when it is running (again swaggo)