swag

package module
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 22, 2018 License: MIT Imports: 16 Imported by: 0

README

swag

Automatically generate RESTful API documentation with Swagger 2.0 for Go.

Travis branch Codecov branch Go Report Card GoDoc

What is swag?

swag converts Go annotations to Swagger Documentation 2.0. And provides a variety of builtin web framework lib. Let you can quickly integrated in existing golang project(using Swagger UI) .

Contents

Generate Swagger 2.0 docs

  1. Add comments to your API source code, See Declarative Comments Format

  2. Download swag by using:

$ go get -u github.com/swaggo/swag/cmd/swag
  1. Run the swag in project root folder which contains main.go file, The swag will parse your comments and generate required files(docs folder and docs/doc.go).
$ swag init

How to use it with gin?

  1. After using swag to generate Swagger 2.0 docs. Import following packages:
import "github.com/swaggo/gin-swagger" // gin-swagger middleware
import "github.com/swaggo/gin-swagger/swaggerFiles" // swagger embed files

  1. Added API Operation annotations in main.go code:
package main

import (
	"github.com/gin-gonic/gin"
	"github.com/swaggo/gin-swagger"
	"github.com/swaggo/gin-swagger/swaggerFiles"

	_ "github.com/swaggo/gin-swagger/example/docs" // docs is generated by Swag CLI, you have to import it.
)

// @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 /v2
func main() {
	r := gin.New()

	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	r.Run()
}
  1. Added General API Info annotations in handler/controller code
// @Summary Add a new pet to the store
// @Description get string by ID
// @ID get-string-by-int
// @Accept  json
// @Produce  json
// @Param   some_id     path    int     true        "Some ID"
// @Success 200 {string} string	"ok"
// @Failure 400 {object} web.APIError "We need ID!!"
// @Failure 404 {object} web.APIError "Can not find ID"
// @Router /testapi/get-string-by-int/{some_id} [get]
func GetStringByInt(c *gin.Context) {
	//write your code
}

// @Description get struct array by ID
// @ID get-struct-array-by-string
// @Accept  json
// @Produce  json
// @Param   some_id     path    string     true        "Some ID"
// @Param   offset     query    int     true        "Offset"
// @Param   limit      query    int     true        "Offset"
// @Success 200 {string} string	"ok"
// @Failure 400 {object} web.APIError "We need ID!!"
// @Failure 404 {object} web.APIError "Can not find ID"
// @Router /testapi/get-struct-array-by-string/{some_id} [get]
func GetStructArrayByString(c *gin.Context) {
	//write your code
}

type Pet3 struct {
	ID int `json:"id"`
}

  1. Run it, and browser to http://localhost:8080/swagger/index.html. You will see Swagger 2.0 Api documents as bellow:

swagger_index.html

Declarative Comments Format

General API Info
annotation description
title Required. The title of the application.
version Required. Provides the version of the application API.
description A short description of the application.
termsOfService The Terms of Service for the API.
contact.name The contact information for the exposed API.
contact.url The URL pointing to the contact information. MUST be in the format of a URL.
contact.email The email address of the contact person/organization. MUST be in the format of an email address.
license.name Required. The license name used for the API.
license.url A URL to the license used for the API. MUST be in the format of a URL.
host The host (name or ip) serving the API.
BasePath The base path on which the API is served.
API Operation
annotation description
description A verbose explanation of the operation behavior.
id A unique string used to identify the operation. Must be unique among all API operations.
tags A list of tags to each API operation that separated by commas.
summary A short summary of what the operation does.
accept A list of MIME types the APIs can consume. Value MUST be as described under Mime Types.
produce A list of MIME types the APIs can produce. Value MUST be as described under Mime Types.
param Parameters that separated by spaces. param name,param type,data type,is mandatory?,comment
success Success response that separated by spaces. return code,{param type},data type,comment
failure Failure response that separated by spaces. return code,{param type},data type,comment
router Failure response that separated by spaces. path,[httpMethod]
Mime Types
  json
  application/json
  xml
  text/xml
  plain
  text/plain
  html
  text/html
  mpfd
  multipart/form-data
  json-api
  application/vnd.api+json

Supported Web Framework

Limitation

  • Not supported for array of structs
  • Not supported for cross-package models. Only search in project root folder. See #39

TODO

  • supplement better documentation
  • add more example
  • support other web Framework

About the Project

This project was inspired by swagger but simplified the usage of complexity and support a variety of web framework.

Documentation

Overview

Package swag converts Go annotations to Swagger Documentation 2.0. See https://github.com/swaggo/swag for more information about swag.

Index

Constants

View Source
const Name = "swagger"

Variables

This section is empty.

Functions

func CheckSchemaType added in v1.1.1

func CheckSchemaType(typeName string)

func GetSchemes

func GetSchemes(commentLine string) []string

GetSchemes parses swagger schemes for gived commentLine

func ReadDoc

func ReadDoc() (string, error)

func Register

func Register(name string, swagger Swagger)

func TransToValidSchemeType added in v1.1.1

func TransToValidSchemeType(typeName string) string

Types

type Operation

type Operation struct {
	HttpMethod string
	Path       string
	spec.Operation
	// contains filtered or unexported fields
}

Operation describes a single API operation on a path. For more information: https://github.com/swaggo/swag#api-operation

func NewOperation

func NewOperation() *Operation

NewOperation creates a new Operation with default properties. map[int]Response

func (*Operation) ParseAcceptComment

func (operation *Operation) ParseAcceptComment(commentLine string) error

ParseAcceptComment parses comment for gived `accept` comment string.

func (*Operation) ParseComment

func (operation *Operation) ParseComment(comment string) error

ParseComment parses comment for gived comment string and returns error if error occurs.

func (*Operation) ParseEmptyResponseComment

func (operation *Operation) ParseEmptyResponseComment(commentLine string) error

func (*Operation) ParseParamComment

func (operation *Operation) ParseParamComment(commentLine string) error

Parse params return []string of param properties @Param queryText form string true "The email for login"

[param name]    [paramType] [data type]  [is mandatory?]   [Comment]

@Param some_id path int true "Some ID"

func (*Operation) ParseProduceComment

func (operation *Operation) ParseProduceComment(commentLine string) error

ParseProduceComment parses comment for gived `produce` comment string.

func (*Operation) ParseResponseComment

func (operation *Operation) ParseResponseComment(commentLine string) error

ParseResponseComment parses comment for gived `response` comment string.

func (*Operation) ParseRouterComment

func (operation *Operation) ParseRouterComment(commentLine string) error

ParseRouterComment parses comment for gived `router` comment string.

func (*Operation) ParseTagsComment added in v1.1.0

func (operation *Operation) ParseTagsComment(commentLine string)

ParseTagsComment parses comment for gived `tag` comment string.

type Parser

type Parser struct {

	// TypeDefinitions is a map that stores [package name][type name][*ast.TypeSpec]
	TypeDefinitions map[string]map[string]*ast.TypeSpec
	// contains filtered or unexported fields
}

Parser implements a parser for Go source files.

func New

func New() *Parser

New creates a new Parser with default properties.

func (*Parser) GetSwagger

func (parser *Parser) GetSwagger() *spec.Swagger

GetSwagger returns *spec.Swagger which is the root document object for the API specification.

func (*Parser) ParseApi

func (parser *Parser) ParseApi(searchDir string, mainApiFile string)

ParseApi parses general api info for gived searchDir and mainApiFile

func (*Parser) ParseDefinition added in v1.1.1

func (parser *Parser) ParseDefinition(pkgName string, typeSpec *ast.TypeSpec, typeName string)

Build

func (*Parser) ParseDefinitions

func (parser *Parser) ParseDefinitions()

ParseDefinitions parses Swagger Api definitions

func (*Parser) ParseGeneralApiInfo

func (parser *Parser) ParseGeneralApiInfo(mainApiFile string)

ParseGeneralApiInfo parses general api info for gived mainApiFile path

func (*Parser) ParseRouterApiInfo

func (parser *Parser) ParseRouterApiInfo(astFile *ast.File)

ParseRouterApiInfo parses router api info for gived astFile

func (*Parser) ParseType

func (parser *Parser) ParseType(astFile *ast.File)

ParseType parses type info for gived astFile

type Swagger

type Swagger interface {
	ReadDoc() string
}

Directories

Path Synopsis
cmd
example
pet

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL