🧬 fiber middleware to automatically generate RESTful API documentation with Swagger

Swagger

Release Discord Test Security Linter

fiber middleware to automatically generate RESTful API documentation with Swagger

Usage

  1. Add comments to your API source code, See Declarative Comments Format.
  2. Download Swag for Go by using:
go get -u github.com/swaggo/swag/cmd/swag
  1. Run the Swag in your Go project root folder which contains main.go file, Swag will parse comments and generate required files(docs folder and docs/doc.go).
swag init
  1. Download swagger by using:
go get -u github.com/gofiber/swagger

And import following in your code:

import "github.com/gofiber/swagger" // swagger handler

Canonical example:

package main

import (
	"github.com/gofiber/swagger"
	"github.com/gofiber/fiber/v2"

	// docs are generated by Swag CLI, you have to import them.
	// replace with your own docs folder, usually "github.com/username/reponame/docs"
	_ "github.com/gofiber/swagger/example/docs"
)

// @title Fiber Example API
// @version 1.0
// @description This is a sample swagger for Fiber
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.email [email protected]
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:8080
// @BasePath /
func main() {
	app := fiber.New()

	app.Get("/swagger/*", swagger.HandlerDefault) // default

	app.Get("/swagger/*", swagger.New(swagger.Config{ // custom
		URL: "http://example.com/doc.json",
		DeepLinking: false,
		// Expand ("list") or Collapse ("none") tag groups by default
		DocExpansion: "none",
		// Prefill OAuth ClientId on Authorize popup
		OAuth: &swagger.OAuthConfig{
			AppName:  "OAuth Provider",
			ClientId: "21bb4edc-05a7-4afc-86f1-2e151e4ba6e2",
		},
		// Ability to change OAuth2 redirect uri location
		OAuth2RedirectUrl: "http://localhost:8080/swagger/oauth2-redirect.html",
	}))

	app.Listen(":8080")
}
  1. Run it, and browser to http://localhost:8080/swagger, you can see Swagger 2.0 Api documents.
Owner
Fiber
🚀 Fiber is an Express inspired web framework written in Go with 💖
Fiber
Comments
  • Declarative comments format is out-of-date

    Declarative comments format is out-of-date

    The current link to the declarative comments format documentation seems out-of-date. The new one is here. Could you update the README.md with the new link?

  • [Feature request]: accept option to include custom css

    [Feature request]: accept option to include custom css

    I would be neat to be able to set a custom css on top of the existing one, I personally hate the default color theme used by Shagger, and i think mos developers would prefer a dark them for my api's documentations, so i would like to see if that would be possible.

    How?, adding a css string or file descriptor, they would be different fields to differenciate them

  • Swag is not recognized as an internal or external command

    Swag is not recognized as an internal or external command

    My trying to run swag init but I got some command error

    'swag' is not recognized as an internal or external command, operable program or batch file.

    Untitled

    go version 1.18.2 Fiber version 2.33.0

  • feat: add proxy redirect support

    feat: add proxy redirect support

    Closes #3

    Since fiber doesn't handle proxy redirects in its redirect function, I think this may help people to configure Swagger behind a proxy.

    Maybe in the future fiber itself should handle it, just like what the Spring (one of the most used web frameworks in the world) do in its implementation: ForwardedHeaderTransformer.java

    In this PR the proxy prefix is handled only once to match the previous implementation so it will not fix all possible problems (for example accessing the documentation from a gateway and then accessing it from a port-forward at the same time). But I think it is acceptable for now since it will fix the most common one (accessing from the gateway).

  • Reverse Proxy configuration

    Reverse Proxy configuration

    Hello.

    I use a reverse proxy (Istio+Envoy) and I'm unable to configure swagger using fiber correctly.

    I'm configuring the swagger handler like this:

    	app.Get("/docs/*", swagger.HandlerDefault)
    

    But when I try to access it from the proxy, which is a URL like this:

    https://proxy-host/some/custom/path/docs
    

    The current implementation redirects me to:

    https://proxy-host/docs/index.html
    

    Instead of

    https://proxy-host/some/custom/path/docs/index.html
    

    The Try it out button also doesn't works because it is trying to send the request to the incorrect path. It should send the request to https://my-proxy-host/custom/path/channels.

    Screenshot with this example: image

    Also, TrustedProxies and EnableTrustedProxyCheck options don't fix this issue. And even it could fix my reverse proxy doesn't have a fixed IP, which would be impossible to configure using the available options. I think you guys should look how Spring Boot manages this and maybe this is even a fiber issue (fixing the c.Redirect func) instead of a gofiber swagger issue: https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto.webserver.use-behind-a-proxy-server

    Thanks.

  • Ideas for Swagger Middleware

    Ideas for Swagger Middleware

    https://github.com/arsmn/fiber-swagger middleware is great but it doesn't have automatic adding feature. Also it will be optional.

    I think it can be added like this with hooks:

    type UserBody struct{
        Email string `json:"email" swagger:"email,required"`
        Password string `json:"password" swagger:"required"`
    }
    
    
    func main() {
        app := fiber.New()
        swg := swagger.New(app, swagger.Config{})
    
        swg.Add("index", swagger.Schema{
            Description: "home page",
            Tags: string["home","index"],
            Summary: "qwerty",
            Body: UserBody,
        })
    
        app.Get("/", func(c *fiber.Ctx) error {
            var user UserBody
            if err := c.BodyParser(&user); err != nil{
                return err
            }
    
            return c.JSON("👋")
        }).Name("index")
    }
    

    cc @balcieren

Related tags
Documentation side of the spaghetti cutter.
Documentation side of the spaghetti cutter.

spaghetti-analyzer - Win The Fight Against Spaghetti Code Overview spaghetti-analyzer is a command line tool for CI/CD pipelines (and dev machines) th

Jan 12, 2022
Gopi - Simple API for get geo information about your IP Address, Build by go-fiber

gopi Simple API to get information from your IP Address Idea This idea come from IP zxq and literaly i clone it How to download GeoIP2 ? Remember to c

May 27, 2022
The Akita CLI for watching network traffic, automatically generating API specs, and diffing API specs.

Catch breaking changes faster Akita builds models of your APIs to help you: Catch breaking changes on every pull request, including added/removed endp

Jul 1, 2022
HTTP API traffic recording and replay middleware based on GoReplay, can be used for migration and refactoring testing

gorc HTTP API traffic recording and replay middleware based on GoReplay, can be used for migration and refactoring testing. English | 中文 Requirements

Feb 13, 2022
HTTP proxy written in Go. COW can automatically identify blocked sites and use parent proxies to access.

COW (Climb Over the Wall) proxy COW 是一个简化穿墙的 HTTP 代理服务器。它能自动检测被墙网站,仅对这些网站使用二级代理。 English README. 当前版本:0.9.8 CHANGELOG 欢迎在 develop branch 进行开发并发送 pull

Jun 28, 2022
Automatically spawn a reverse shell fully interactive for Linux or Windows victim
Automatically spawn a reverse shell fully interactive for Linux or Windows victim

Girsh (Golang Interactive Reverse SHell) Who didn't get bored of manually typing the few lines to upgrade a reverse shell to a full interactive revers

Jun 27, 2022
Automatically compress podcasts to tiny file sizes for bandwidth constrained devices like cellular.
Automatically compress podcasts to tiny file sizes for bandwidth constrained devices like cellular.

tinycast Automatically compress podcasts to tiny file sizes for bandwidth constrained connections like cellular or satellite.

Jan 15, 2022
dynflare is a tool to automatically update dns records at Cloudflare, when the ip changes.

dynflare dynflare is a tool to automatically update dns records at Cloudflare, when the ip changes. How it works The current ips are determined by ask

Dec 7, 2021
Automatically register a list of domain names, add them to Cloudflare and set DNS records.

NameCannon Automatically register a list of domain names, add them as zones on Cloudflare, then add DNS records. Usage $ ./NameCannon --namesiloSecret

Jan 26, 2022
Attach services to specified networks automatically

Docker swarm network attacher Description docker-swarm-network-attacher aims to solve the problem of sharing a network between unrelated services. Wit

Nov 11, 2021
Automatically update your Windows hosts file with the WSL2 VM IP address

Automatically update your Windows hosts file with the WSL2 VM IP address

Jun 28, 2022
AutoTrackIR will automatically re-enabled your Track IR if flight simulator disabled it. (bug introduce in SU7)

AutoTrackIR AutoTrackIR will automatically re-enable your Track IR if flight simulator disabled it. (bug introduce in SU7) How it works ? It just watc

May 8, 2022
🤖 Automatically scrape PortableApps.com (or official release page) and convert into Edgeless plugin package

Edgeless 自动插件机器人 2 简介 该项目是为了使用 Golang 重新实现 Edgeless 自动插件机器人 特性 (WIP) 完全兼容 Edgeless 自动插件机器人,包括 Tasks,以实现无缝迁移 更快的构建速度 更好的代码结构 更高的拓展性 工作进度 截止至 2021/11/28

Dec 7, 2021
The seed repository for your Flamego middleware modules

seed This repository contains seed files that almost every repository of Flamego middleware module should have. Using the content Create an empty repo

Dec 11, 2021
Mev-boost: A middleware server written in Go

mev-boost A middleware server written in Go, that sits between an ethereum PoS consensus client and an execution client. It allows consensus clients t

Jun 30, 2022
Header Block is a middleware plugin for Traefik to block request and response headers which regex matched by their name and/or value

Header Block is a middleware plugin for Traefik to block request and response headers which regex matched by their name and/or value Conf

May 24, 2022
Log4Shell is a middleware plugin for Traefik which blocks JNDI attacks based on HTTP header values.

Log4Shell Mitigation Log4Shell is a middleware plugin for Traefik which blocks JNDI attacks based on HTTP header values. Related to the Log4J CVE: htt

Apr 17, 2022
Middleware for Blocking IP ranges by inserting CIDR Blocks and searching IPs through those blocks

firewall Middleware for Blocking IP ranges by inserting CIDR Blocks and searching IPs through those blocks. Features Easy to use Efficient and Fast Co

May 20, 2022