技術向上

プログラミングの学び、気になるテクノロジーやビジネストレンドを発信

swaggoの導入【Go】【Swagger】

swaggoという外部パッケージを利用することで、Swaggerを使って作成済みのGoのソースコードからAPIドキュメントを作成できます。

install

パッケージをインストールします。

$ go get github.com/swaggo/swag/cmd/swag


APIに関する記述を規定のフォーマットに従って、コメントとして記入します。
コメントの記入については公式を確認ください。


main.goがあるディレクトリで下記コマンドを実行し、swagのdocsを生成します。

$ swag init


net/httpパッケージを利用している場合は下記パッケージをインストールします。
パッケージによって手順が異なるので、詳細は公式を参照ください。

$ go get -u github.com/swaggo/http-swagger


ルーティングを行なっているパッケージのimportに下記を追加します。
ルートはご自身の環境に従って記入ください。

_ "github.com/~/docs"    // swag initで生成したdocs。
httpSwagger "github.com/swaggo/http-swagger"


読み込んだdocsの内容がswaggerUIに出力されます。
ルーティングに下記を追加します。

r.Get("/swagger/*", httpSwagger.WrapHandler)


指定したルートにアクセスすると、swaggerUIが表示されるかと思います。

基本情報の定義

main.goに、base urlや基本情報を定義します。
BasePathに記載した内容は後述するAPIのどのルーティングにも最初に適用されるurlになります。
APIの定義が間違っていないのに、レスポンスがnot found になる場合は確認してみると良いかもしれません。

// @title Swagger Example API
// @version 1.0
// @description This is a sample server celler 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 localhost:3001
// @BasePath /noauth/v1

// @securityDefinitions.basic BasicAuth

// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name Authorization

// @securitydefinitions.oauth2.application OAuth2Application
// @tokenUrl https://example.com/oauth/token
// @scope.write Grants write access
// @scope.admin Grants read and write access to administrative information

// @securitydefinitions.oauth2.implicit OAuth2Implicit
// @authorizationurl https://example.com/oauth/authorize
// @scope.write Grants write access
// @scope.admin Grants read and write access to administrative information

// @securitydefinitions.oauth2.password OAuth2Password
// @tokenUrl https://example.com/oauth/token
// @scope.read Grants read access
// @scope.write Grants write access
// @scope.admin Grants read and write access to administrative information

// @securitydefinitions.oauth2.accessCode OAuth2AccessCode
// @tokenUrl https://example.com/oauth/token
// @authorizationurl https://example.com/oauth/authorize
// @scope.admin Grants read and write access to administrative information

var addr = ":3001"

func main() {
...
}


APIの定義

ルーティングで指定しているメソッドが記述されている箇所の直上(空行があってはなりません)にルールに従ったコメントを記載することで、swagger UI上に表示されるようになります。

// GetCSTimetableDate godoc
// @Summary Get a accCSTimetable of a specific day
// @Description get string by ID
// @Accept  json
// @Produce  json
// @Param  cs_date body model.CSDate true "来店予約日"
// @Success 200 {string} string "ok"
// @Router /reservations/capacity/date [post]
func (h *CSHandler) PostCSTimetableDate(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context()

    var csDate model.CSDate
    err := handler.GetJSON(r, &csDate)
    if err != nil {
        h.handleError(ctx, w, http.StatusBadRequest, "handler.GetJSON: "+err.Error())
        return
    }
    ...
}


@Paramですが、複数の値を付与するならば、objectやarrayを型に指定することができます。メソッドで使うオリジナルの型を定義することが多いかと思いますが、その型を指定することもできます。その時は「パラメータ名 body オリジナルの型」のように記述します。上記例では型の定義を独立させたclean architectureを採用しているプロジェクトからの抜粋のため、型名に「model.」と記載されています。


GitHub - swaggo/swag: Automatically generate RESTful API documentation with Swagger 2.0 for Go.

GitHub - swaggo/http-swagger: Default net/http wrapper to automatically generate RESTful API documentation with Swagger 2.0.

[swaggo]GoのGoDocを書いたら、Swaggerを出せるやばいやつ - Qiita