swag

package module
v1.1.2-0...-ac680a8 Latest Latest
Warning

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

Go to latest
Published: May 25, 2018 License: MIT Imports: 18 Imported by: 2

README

swag

swaggo

Automatically generate RESTful API documentation with Swagger 2.0 for Go.

Travis Status Coverage Status Go Report Card codebeat badge Go Doc

gopher image source is tenntenn/gopher-stickers. It has licenses creative commons licensing.

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) .

Status of implementations

Swagger 2.0 document

  • Basic Structure
  • API Host and Base Path
  • Paths and Operations
  • Describing Parameters
  • Describing Request Body
  • Describing Responses
  • MIME Types
  • Authentication
    • Basic Authentication
    • API Keys
  • Adding Examples
  • File Upload
  • Enums
  • Grouping Operations With Tags
  • Swagger Extensions

Document

Example

swaggo + gin

Getting started

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

  2. Download swag by using:

$ go get -u github.com/AmirSoleimani/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?

This example source here.

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

Supported Web Framework in generate swagger middleware

2.Added General API Info annotations in main.go code:

// @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:8080
// @BasePath /api/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

func main() {
	r := gin.Default()

	c := controller.NewController()

	v1 := r.Group("/api/v1")
	{
		accounts := v1.Group("/accounts")
		{
			accounts.GET(":id", c.ShowAccount)
			accounts.GET("", c.ListAccounts)
			accounts.POST("", c.AddAccount)
			accounts.DELETE(":id", c.DeleteAccount)
			accounts.PATCH(":id", c.UpdateAccount)
			accounts.POST(":id/images", c.UploadAccountImage)
		}
    //...
	}
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
	r.Run(":8080")
}
//...

3.Added API Operation annotations in controller code

package controller

import (
	"fmt"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/AmirSoleimani/swag/example/celler/httputil"
	"github.com/AmirSoleimani/swag/example/celler/model"
)

// ShowAccount godoc
// @Summary Show a account
// @Description get string by ID
// @ID get-string-by-int
// @Accept  json
// @Produce  json
// @Param id path int true "Account ID"
// @Success 200 {object} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts/{id} [get]
func (c *Controller) ShowAccount(ctx *gin.Context) {
	id := ctx.Param("id")
	aid, err := strconv.Atoi(id)
	if err != nil {
		httputil.NewError(ctx, http.StatusBadRequest, err)
		return
	}
	account, err := model.AccountOne(aid)
	if err != nil {
		httputil.NewError(ctx, http.StatusNotFound, err)
		return
	}
	ctx.JSON(http.StatusOK, account)
}

// ListAccounts godoc
// @Summary List accounts
// @Description get accounts
// @Accept  json
// @Produce  json
// @Param q query string false "name search by q"
// @Success 200 {array} model.Paginate {Result:model.accounts}
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts [get]
func (c *Controller) ListAccounts(ctx *gin.Context) {
	q := ctx.Request.URL.Query().Get("q")
	accounts, err := model.AccountsAll(q)
	if err != nil {
		httputil.NewError(ctx, http.StatusNotFound, err)
		return
	}
	ctx.JSON(http.StatusOK, accounts)
}

//...

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

swagger_index.html

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/AmirSoleimani/swag for more information about swag.

Index

Constants

View Source
const Name = "swagger"

Name TODO: NEEDS COMMENT INFO

View Source
const Version = "v1.3.0"

Version for swag

Variables

This section is empty.

Functions

func CheckSchemaType

func CheckSchemaType(typeName string)

CheckSchemaType TODO: NEEDS COMMENT INFO

func GetSchemes

func GetSchemes(commentLine string) []string

GetSchemes parses swagger schemes for gived commentLine

func ReadDoc

func ReadDoc() (string, error)

ReadDoc TODO: NEEDS COMMENT INFO

func Register

func Register(name string, swagger Swagger)

Register TODO: NEEDS COMMENT INFO

func TransToValidSchemeType

func TransToValidSchemeType(typeName string) string

TransToValidSchemeType is int type will transfer to integer which is goswagger supported type

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/AmirSoleimani/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

ParseEmptyResponseComment TODO: NEEDS COMMENT INFO

func (*Operation) ParseParamComment

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

ParseParamComment 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) ParseSecurityComment

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

ParseSecurityComment parses comment for gived `security` comment string.

func (*Operation) ParseTagsComment

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

	// InterfaceDefinitions is a map that stores [fieldname]=>DefinitionsName
	InterfaceDefinitions map[string]string

	PropNamingStrategy string
	// 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

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

ParseDefinition TODO: NEEDS COMMENT INFO

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
}

Swagger TODO: NEEDS COMMENT INFO

Directories

Path Synopsis
cmd
example

Jump to

Keyboard shortcuts

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