본문 바로가기

개발

Golang - Swagger 연동

swag github : https://github.com/swaggo/swag?tab=readme-ov-file#getting-started
swag은 golang에서 swagger 문서를 쉽게 작성할 수 있도록 도와주는 라이브러리입니다.
swag은 echo로 개발된 HTTP Server도 지원하기 때문에 swag을 통해 API 문서를 작성해보겠습니다.

1. swag 설치

다음 명령어를 통해 최신 버전의 swag을 설치합니다.

go install github.com/swaggo/swag/cmd/swag@latest

2. main.go 수정

swag은 main.go에 작성된 주석을 파싱하여 swagger 문서를 생성해줍니다.
다음과 같은 코드를 작성합니다.

package main

import (
    "net/http"

    "github.com/labstack/echo/v4"
    "github.com/labstack/echo/v4/middleware"
    echoSwagger "github.com/swaggo/echo-swagger"

    _ "example/api-server/docs"
)

type CustomResponse struct {
    Key string `json:"key"`
}

// @title            Golang API Server
// @version        1.0
// @description    This is a sample server using golang.
func main() {

    e := echo.New()

    e.Use(middleware.Logger())
    e.Use(middleware.Recover())

    e.GET("/hello", hello)
    e.GET("/swagger/*", echoSwagger.WrapHandler)

    e.Logger.Fatal(e.Start(":3000"))
}

// Hello godoc
//
//    @Summary        Get Hello
//    @Description    Get Hello by api call
//    @Accept            json
//    @Produce        json
//    @Success        200    {object}    CustomResponse
//    @Failure        400    {object}    error
//    @Failure        404    {object}    error
//    @Failure        500    {object}    error
//    @Router            /hello [get]
func hello(c echo.Context) error {
    response := &CustomResponse{
        Key: "Hello world!",
    }
    return c.JSON(http.StatusOK, response)
}

main 함수 위에 많은 주석이 달린것을 확인할 수 있습니다.

코드를 하나씩 살펴봅시다.

import (
    "net/http"

    "github.com/labstack/echo/v4"
    "github.com/labstack/echo/v4/middleware"
    echoSwagger "github.com/swaggo/echo-swagger"

    _ "example/api-server/docs"
)

swag init을 하는 경우 doc 디렉토리가 생성됩니다.
이 doc 디렉토리를 import 해주어야합니다.
따라서, _ 뒤에 나오는 디렉토리의 경우 자신의 프로젝트 루트 디렉토리를 바라보고 있어야합니다.
저의 경우 go.mod에 적혀있는 프로젝트 이름이 example/api-server 이기 때문에, example/api-server 로 설정했습니다.

// @title            Golang API Server
// @version        1.0
// @description    This is a sample server using golang.

이 주석은 swagger의 헤더부분에 나오는 정보를 작성합니다.

e.GET("/swagger/*", echoSwagger.WrapHandler)

/swagger 라는 경로에 swagger 문서를 설정합니다.

// Hello godoc
//
//    @Summary        Get Hello
//    @Description    Get Hello by api call
//    @Accept            json
//    @Produce        json
//    @Success        200    {object}    CustomResponse
//    @Failure        400    {object}    error
//    @Failure        404    {object}    error
//    @Failure        500    {object}    error
//    @Router            /hello [get]

특정 API Path에 대해서 swagger 문서를 작성합니다.

3. swag init & go get . & go run main.go

swag init을 통해 swagger 문서를 생성합니다.

swag init
2024/09/19 16:04:07 Generate swagger docs....
2024/09/19 16:04:07 Generate general API Info, search dir:./
2024/09/19 16:04:07 create docs.go at docs/docs.go
2024/09/19 16:04:07 create swagger.json at docs/swagger.json
2024/09/19 16:04:07 create swagger.yaml at docs/swagger.yaml

명령어를 실행한 뒤 docs/ 디렉토리가 생성된 것을 볼 수 있습니다.
내부에는 swagger 문서에 관련된 파일들이 생성되어있습니다.

go get . 을 통해 필요한 패키지를 다운로드합니다.

go get .                                         
go: downloading github.com/swaggo/echo-swagger v1.4.1
go: downloading github.com/swaggo/swag v1.8.12
go: downloading github.com/ghodss/yaml v1.0.0
go: downloading github.com/swaggo/files/v2 v2.0.0
go: downloading golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d
go: downloading golang.org/x/net v0.25.0
go: added github.com/KyleBanks/depth v1.2.1
go: added github.com/PuerkitoBio/purell v1.1.1
go: added github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578
go: added github.com/ghodss/yaml v1.0.0
go: added github.com/go-openapi/jsonpointer v0.19.5
go: added github.com/go-openapi/jsonreference v0.19.6
go: added github.com/go-openapi/spec v0.20.4
go: added github.com/go-openapi/swag v0.19.15
go: added github.com/josharian/intern v1.0.0
go: added github.com/mailru/easyjson v0.7.7
go: added github.com/swaggo/echo-swagger v1.4.1
go: added github.com/swaggo/files/v2 v2.0.0
go: added github.com/swaggo/swag v1.8.12
go: upgraded golang.org/x/net v0.24.0 => v0.25.0
go: added gopkg.in/yaml.v2 v2.4.0

go run main.go 를 통해 서버를 실행합니다.

go run main.go

   ____    __
  / __/___/ /  ___
 / _// __/ _ \/ _ \
/___/\__/_//_/\___/ v4.12.0
High performance, minimalist Go web framework
https://echo.labstack.com
____________________________________O/_______
                                    O\
⇨ http server started on [::]:3000

4. 테스트

브라우저를 통해서 http://localhost:3000/swagger/index.html 에 접속합니다.
다음 페이지가 노출되면 성공입니다.

 

'개발' 카테고리의 다른 글

Golang - echo를 활용한 API Server 만들기  (0) 2024.09.21
Golang - Connect to MongoDB  (2) 2024.09.18
Golang - Connect to MySQL  (1) 2024.09.18
Golang - 프로젝트 시작  (0) 2024.09.18
Q Learning과 DQN  (0) 2023.12.09