swag

package module
v0.0.0-...-8255161 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2019 License: Apache-2.0 Imports: 3 Imported by: 0

README

swag

Forked from & all credit to Savaki

GoDoc

swag is a lightweight library to generate swagger json for Go projects.

No code generation, no framework constraints, just a simple swagger definition.

swag is heavily geared towards generating REST/JSON apis.

Installation

go get github.com/music-tribe/swag

Status

This package should be considered a release candidate. No further package changes are expected at this point.

Concepts

swag uses functional options to generate both the swagger endpoints and the swagger definition. Where possible swag attempts to use reasonable defaults that may be overridden by the user.

Endpoints

swag provides a separate package, endpoint, to generate swagger endpoints. These endpoints can be passed to the swagger definition generate via swag.Endpoints(...)

In this simple example, we generate an endpoint to retrieve all pets. The only required fields for an endpoint are the method, path, and the summary.

allPets := endpoint.New("get", "/pet", "Return all the pets") 

However, it'll probably be useful if you include definitions of what GET /pet returns:

allPets := endpoint.New("get", "/pet", "Return all the pets",
  endpoint.Response(http.StatusOk, Pet{}, "Successful operation"),
  endpoint.Response(http.StatusInternalServerError, Error{}, "Oops ... something went wrong"),
) 

Refer to the godoc for a list of all the endpoint options

Walk

As a convenience to users, *swagger.Api implements a Walk method to simplify traversal of all the endpoints. See the complete example below for how Walk can be used to bind endpoints to the router.

api := swag.New(
    swag.Title("Swagger Petstore"),
    swag.Endpoints(post, get),
)

// iterate over each endpoint, if we've defined a handler, we can use it to bind to the router.  We're using ```gin``
// in this example, but any web framework will do.
// 
api.Walk(func(path string, endpoint *swagger.Endpoint) {
    h := endpoint.Handler.(func(c *gin.Context))
    path = swag.ColonPath(path)
    router.Handle(endpoint.Method, path, h)
})

Complete Example

func handlePet(w http.ResponseWriter, _ *http.Request) {
	// your code here
}

type Pet struct {
	Id        int64    `json:"id"`
	Name      string   `json:"name"`
	PhotoUrls []string `json:"photoUrls"`
	Tags      []string `json:"tags"`
}

func main() {
    // define our endpoints
    // 
    post := endpoint.New("post", "/pet", "Add a new pet to the store",
        endpoint.Handler(handle),
        endpoint.Description("Additional information on adding a pet to the store"),
        endpoint.Body(Pet{}, "Pet object that needs to be added to the store", true),
        endpoint.Response(http.StatusOK, Pet{}, "Successfully added pet"),
    )
    get := endpoint.New("get", "/pet/{petId}", "Find pet by ID",
        endpoint.Handler(handle),
        endpoint.Path("petId", "integer", "ID of pet to return", true),
        endpoint.Response(http.StatusOK, Pet{}, "successful operation"),
    )
    
    // define the swagger api that will contain our endpoints
    // 
    api := swag.New(
      swag.Title("Swagger Petstore"),
      swag.Endpoints(post, get),
    )
    
    // iterate over each endpoint and add them to the default server mux
    // 
    for path, endpoints := range api.Paths {
      http.Handle(path, endpoints)
    }
    
    // use the api to server the swagger.json file
    // 
    enableCors := true
    http.Handle("/swagger", api.Handler(enableCors))
    
    http.ListenAndServe(":8080", nil)
}

Additional Examples

Examples for popular web frameworks can be found in the examples directory:

Documentation

Overview

Copyright 2017 Matt Ho

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ColonPath

func ColonPath(path string) string

ColonPath accepts a swagger path e.g. /api/orgs/{org} and returns a colon identified path e.g. /api/org/:org

func New

func New(options ...Option) *swagger.API

New constructs a new api builder

Types

type Builder

type Builder struct {
	API *swagger.API
}

Builder uses the builder pattern to generate a swagger definition

type Option

type Option func(builder *Builder)

Option provides configuration options to the swagger api builder

func BasePath

func BasePath(v string) Option

BasePath sets basePath

func ContactEmail

func ContactEmail(v string) Option

ContactEmail sets info.contact.email

func Description

func Description(v string) Option

Description sets info.description

func Endpoints

func Endpoints(endpoints ...*swagger.Endpoint) Option

Endpoints allows the endpoints to be added dynamically to the Api

func Host

func Host(v string) Option

Host specifies the host field

func License

func License(name, url string) Option

License sets both info.license.name and info.license.url

func Schemes

func Schemes(v ...string) Option

Schemes sets the scheme

func Security

func Security(scheme string, scopes ...string) Option

Security sets a default security scheme for all endpoints in the API.

func SecurityScheme

func SecurityScheme(name string, options ...swagger.SecuritySchemeOption) Option

SecurityScheme creates a new security definition for the API.

func Tag

func Tag(name, description string, options ...TagOption) Option

Tag adds a tag to the swagger api

func TermsOfService

func TermsOfService(v string) Option

TermsOfService sets info.termsOfService

func Title

func Title(v string) Option

Title sets info.title

func Version

func Version(v string) Option

Version sets info.version

type TagOption

type TagOption func(tag *swagger.Tag)

TagOption provides additional customizations to the #Tag option

func TagDescription

func TagDescription(v string) TagOption

TagDescription sets externalDocs.description on the tag field

func TagURL

func TagURL(v string) TagOption

TagURL sets externalDocs.url on the tag field

Directories

Path Synopsis
examples
gin

Jump to

Keyboard shortcuts

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