Giter VIP home page Giter VIP logo

swag's Introduction

swag

GoDoc Build Status

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/miketonks/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)
})

Custom Types

For types implementing json.Marshaler whose JSON output does not match their Go types (such as time.Time), it is possible to override the default scanning of types and define a property manually.

For example:

type Person struct {
  Name string `json:"name"`
  Birthday time.Time `json:"birthday"`
}

func main() {
  RegisterCustomType(time.Time{}, Property{
    Type: "string",
    Format: "date-time",
  })
}

time.Time is automatically registered as a custom type.

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:

swag's People

Contributors

savaki avatar miketonks avatar bjyoungblood avatar victorvess avatar

Watchers

James Cloos avatar Geoff Tipton avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.