Giter Site home page Giter Site logo

gin-swagger's Introduction

gin-swagger - DRY templates for go-swagger

gin-swagger is a tool assisting in writing golang REST APIs based on a API First Principle. Given a swagger spec of your REST API, gin-swagger can generate all the boring boilerplate stuff for you, so you only have to implement the core business logic of the API.

It is based on go-swagger which is used for the code generation.

Install

Dependencies

  • go-bindata - Optional only needed if you are changing gin-swagger.

Once you have the dependencies in place you can simply run go get to install gin-swagger.

$ go get github.com/mikkeloscar/gin-swagger
$ gin-swagger --help
usage: gin-swagger --application=APPLICATION [<flags>]

Flags:
      --help                     Show context-sensitive help (also try --help-long and --help-man).
  -A, --application=APPLICATION  Name of the application (passed directly to swagger).
  -f, --spec="./swagger.json"    the spec file to use.

How it works

gin-swagger generates a gin based REST API given a swagger spec.

Assuming the following swagger spec:

swagger: '2.0'
info:
  version: "0.0.1"
  title: My API
schemes:
    - "https"
basePath: /
produces:
  - application/json
consumes:
  - application/json
paths:
  '/persons/{name}':
    get:
      summary: get Person
      tags:
        - Person
      operationId: getPerson
      responses:
        200:
          description: Person by name.
          schema:
            '$ref': '#/definitions/Person'
parameters:
  name:
    name: name
    in: path
    type: string
    required: true
    pattern: "^[a-z][a-z0-9]$"
definitions:
  Person:
    type: object
    properties:
      name:
        type: string

You can generate the REST API using the following command:

$ gin-swagger -A my-api -f swagger.yaml

This will generate two folders models/ and restapi/. models/ contains model structs based on the definitions defined in your swagger file, including model validation, this is generated by go-swagger. restapi/ will contain everything generated by gin-swagger and can be overwritten when updating and regenerating your swagger spec. restapi/api.go will contain a generated Service interface which is all you have to implement in order to add logic to your REST api.

Given the above swagger spec, the Service interface will look like this:

type Service interface {
    Healthy() bool
    GetPerson(ctx *gin.Context, params *persons.GetPersonParams) *api.Response
}

The Healthy() bool method should return true if the service is considered healthy. The return value is used by the default health endpoint /healthz provided by gin-swagger.

The GetPerson() method should implement the business logic of the /persons/{name} path of your REST API.

A simple service implementation looks like this:

type mySvc struct {
    health bool
}

func (m *mySvc) GetPerson(ctx *gin.Context, params *persons.GetPersonParams) *api.Response {
    return &api.Response{
        Code: http.StatusOK,
        Body: &models.Person{Name: params.Name},
    }
}

func (m *mySvc) Healthy() bool {
    return m.health
}

With the service implemented the only thing left to do is plug it into gin-swagger and run it from your main.go (or wherever you like):

package main

import ...

var apiConfig restapi.Config

func main() {
    err := apiConfig.Parse()
    if err != nil {
        log.Fatal(err)
    }
    svc := &mySvc{health: true}
    api := restapi.NewAPI(svc, &apiConfig)
    err = api.RunWithSigHandler()
    if err != nil {
        log.Fatal(err)
    }
}

restapi.Config is a default config object defined by gin-swagger it lets you configure default options through commandline flags when starting the server. For instance you can tell the server to serve HTTP only with the --insecure-http flag (default is to serve HTTPS).

For a full example see the example folder.

Features

  • Validate + bind input to gin ctx.
    • bind body input.
      • [Nice to have] custom input Models with required fields.
    • bind params input.
    • bind query params input.
    • consume more than application/json
  • Security.
    • basic
    • apiKey
    • OAuth2
      • password (Bearer token)
      • accessCode
      • application
      • implicit
    • Auth chain
    • Custom authorize on individual routes.
  • Set custom middleware on each router Pre/post 'main' handler.
    • Use case pre: custom authorization pre handler.
    • Use case post: audit report events post handler.
  • Ginize generated code.
  • Set and get user info (uid, realm) from gin context.
  • Response helper functions
  • Default metrics (prometheus)
  • OpenTracing support

gin-swagger's People

Contributors

cugu avatar dependabot[bot] avatar devil-maycry avatar firejump avatar jbellmann avatar mikkeloscar avatar raffo avatar superpan avatar tuxlife 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.