728x90

다음 내용은 윈도우 환경 기준으로 설명합니다. 

 

1) swag 명령어 다운받기

go get -u github.com/swaggo/swag/cmd/swag

2) command에서 swag 명령어 실행한다.

swag 명령어를 실행했을 때 아래와 같이 출력되면 정상적으로 설치된 것입니다.

swag command

3) gin-swagger 다운받기

go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/files
728x90

4) restapi 구현하고, swagger적용하기

// 주의사항 : 반드시 SwaggerInfo를 코드로 지정해지만 doc.json 정상적으로 조회됩니다

//(무슨 문제인지 소스까보기 귀찮아서 그냥 코드로 값을 설정하는 방식을 사용할랍니다.)
docs.SwaggerInfo.Title = "Swagger Example API"

 

main() 함수 주석 중에 @title ~ @BasePath까지, HelloHandler()함수 주석 중에 @Summay ~ @Failure 문서화되는 항목입니다. 각 항목들의 정의 다음에서 설명되어 있습니다. 

https://github.com/swaggo/swag#api-operation

 

//main.go
package main

import (
	"net/http"
	"go_swagger/docs"
    
	"github.com/gin-gonic/gin"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
)

/* 아래 항목이 swagger에 의해 문서화 된다. */
// @title Swagger Example API
// @version 1.0
// @description This is a sample server Petstore server.
// @termsOfService http://swagger.io/terms/

// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io

// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html

// @host petstore.swagger.io
// @BasePath /api/v1
func main() {
	r := gin.Default()

	//코드로 SwaggerInfo 속성을 지정해지만 doc.json 정상적으로 조회된다.
	docs.SwaggerInfo.Title = "Swagger Example API"

    // 127.0.0.1:8080/docs/index.html 주로 swagger로 생성된 문서를 확인 수 있다. 
	r.GET("/docs/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	v1Group := r.Group("/api/v1")
	{
		v1Group.GET("/hello/:name", HelloHandler)
	}
	r.Run("localhost:8080")
}

type User struct {
	Id   int    `json:"id" example:"1"`      //유저ID
	Name string `json:"name" example:"John"` //이름
	Age  int    `json:"age" example:"10"`    //나이
}

/* 아래 항목이 swagger에 의해 문서화 된다. */
// HelloHandler godoc
// @Summary 요약 기재
// @Description 상세한 설명 기재
// @name get-string-by-int
// @Accept  json
// @Produce  json
// @Param name path string true "User name"
// @Router /api/v1/hello/{name} [get]
// @Success 200 {object} User
// @Failure 400
func HelloHandler(c *gin.Context) {
	name := c.Param("name")
	if name == "" {
		c.JSON(http.StatusBadRequest, gin.H{"user": ""})
	} else {
		user := User{Id: 1, Name: name, Age: 20}
		c.JSON(http.StatusOK, gin.H{"user": user})
	}
}

 

5) main.go 파일이 있는 경로에서 swag init 명령어로 작성화 소스코드의 문서 작성한다. 

swag init 정상적으로 실행되었다면 아래와 같이 출력되고, ./docs 폴더에 3개의 문화를 위한 소스와 메타정보를 포함한 파일이 생성됩니다. 

<생성된 파일>

./docs/docs.go

./docs/swagger.json

./docs/swagger.yaml

swag init 명령어 실행결과 (swag init command result)

./docs/swagger.json 파일 

{
    "swagger": "2.0",
    "info": {
        "description": "This is a sample server Petstore server.",
        "title": "Swagger Example API",
        "termsOfService": "http://swagger.io/terms/",
        "contact": {
            "name": "API Support",
            "url": "http://www.swagger.io/support",
            "email": "support@swagger.io"
        },
        "license": {
            "name": "Apache 2.0",
            "url": "http://www.apache.org/licenses/LICENSE-2.0.html"
        },
        "version": "1.0"
    },
    "host": "petstore.swagger.io",
    "basePath": "/api/v1",
    "paths": {
        "/api/v1/hello/{name}": {
            "get": {
                "description": "상세한 설명 기재",
                "consumes": [
                    "application/json"
                ],
                "produces": [
                    "application/json"
                ],
                "summary": "요약 기재",
                "parameters": [
                    {
                        "type": "string",
                        "description": "User name",
                        "name": "name",
                        "in": "path",
                        "required": true
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK",
                        "schema": {
                            "$ref": "#/definitions/main.User"
                        }
                    },
                    "400": {
                        "description": ""
                    }
                }
            }
        }
    },
    "definitions": {
        "main.User": {
            "type": "object",
            "properties": {
                "age": {
                    "description": "나이",
                    "type": "integer",
                    "example": 10
                },
                "id": {
                    "description": "유저ID",
                    "type": "integer",
                    "example": 1
                },
                "name": {
                    "description": "이름",
                    "type": "string",
                    "example": "John"
                }
            }
        }
    }
}

6) go run main.go 명령어로 작성한 go코드를 실행한다. 

go run main.go result

 

브라우저에서 다음 URL을 실행하면 아래와 같은 결과물을 확인할 수 있습니다.

새로운 API가 추가되거나 변경사항이 있는 swag init 명령어 실행하면 아래 URL의 문서가 업데이트 됩니다. 

http://localhost:8080/docs/index.html

go + gin + swagger 문서화 적용 예시

 

참고사이트 

https://github.com/swaggo/gin-swagger

 

 

 

728x90
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기
반응형