Skip to content

NKI-AI/rules-go-swag

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Swag Rules for Bazel

Bazel rules for generating Swagger/OpenAPI documentation from Go code annotations using swag.

This follows the fiber-swagger workflow where you annotate your Go code with Swagger comments and generate swagger.json, swagger.yaml, and docs.go files.

Requirements

  • Bazel 7.0 or later (uses MODULE.bazel)
  • Go code with Swag annotations

Setup

In your MODULE.bazel

bazel_dep(name = "rules_go_swagger", version = "1.0.0")

# If using local version:
local_path_override(
    module_name = "rules_go_swagger",
    path = "path/to/rules_go_swagger",
)

# Register swag tool
swag = use_extension("@rules_go_swagger//go/swagger:extensions.bzl", "swag_extension")
use_repo(swag, "com_github_swaggo_swag_repository_tools")

Usage

Start Using It

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

  2. Use the swag_init_script rule to generate documentation.

Example: Generate Swagger Docs

In your BUILD.bazel:

load("@rules_go_swagger//go/swagger:def.bzl", "swag_init_script")

swag_init_script(
    name = "generate_swagger",
    general_info = "cmd/server/main.go",
    output_dir = "internal/docs",
    search_dirs = [
        "cmd/server",
        "internal/handlers",
    ],
    parse_dependency = True,
    parse_internal = True,
)

Run the generator:

bazel run //:generate_swagger

This will:

  1. Scan your Go source files for Swagger annotations
  2. Generate swagger.json, swagger.yaml, and docs.go in the internal/docs/ directory

Swagger Annotations Example

In your main.go:

package main

import (
	"log"

	"github.com/gofiber/fiber/v2"
	fiberSwagger "github.com/swaggo/fiber-swagger"

	_ "github.com/example/myapp/internal/docs" // Generated by swag
)

// @title           Swagger Example API
// @version         1.0
// @description     This is a sample server API.
// @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.apikey BearerAuth
// @in header
// @name Authorization
func main() {
	app := fiber.New()

	// Swagger endpoint
	app.Get("/swagger/*", fiberSwagger.WrapHandler)

	if err := app.Listen(":8080"); err != nil {
		log.Fatalf("fiber.Listen failed: %s", err)
	}
}

In your handler files:

// @Summary      Get user by ID
// @Description  Retrieve a user's information by their ID
// @Tags         users
// @Accept       json
// @Produce      json
// @Param        id   path      string  true  "User ID"
// @Success      200  {object}  models.User
// @Failure      404  {object}  models.ErrorResponse
// @Router       /users/{id} [get]
// @Security     BearerAuth
func GetUser(c *fiber.Ctx) error {
    // ...
}

Advanced Configuration

The swag_init_script rule supports various options:

swag_init_script(
    name = "generate_swagger",
    general_info = "cmd/server/main.go",      # Main file with @title, @version, etc.
    output_dir = "internal/docs",              # Where to write generated files
    search_dirs = ["cmd", "internal"],         # Directories to scan
    parse_dependency = True,                   # Parse dependencies from go.mod
    parse_internal = True,                     # Parse internal packages
    parse_vendor = False,                      # Parse vendor folder
    output_types = ["go", "json", "yaml"],     # Which files to generate
)

Integrating with Web Frameworks (Optional)

After generating the docs, you can serve them with Swagger UI using framework-specific middleware:

Fiber

go get -u github.com/swaggo/fiber-swagger
import (
    fiberSwagger "github.com/swaggo/fiber-swagger"
    _ "github.com/example/myapp/internal/docs"
)

app.Get("/swagger/*", fiberSwagger.WrapHandler)

Gin

go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/files
import (
    ginSwagger "github.com/swaggo/gin-swagger"
    "github.com/swaggo/files"
    _ "github.com/example/myapp/internal/docs"
)

router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

Browse to http://localhost:8080/swagger/index.html to view your API documentation.

Note: The Bazel rules generate the documentation files - you don't need framework integration if you just want the swagger.json file!

Examples

This repository includes two complete working examples:

Both examples implement identical APIs with the same Swagger annotations, demonstrating that Swag is framework-agnostic. The only difference is the web framework - the documentation generation process is identical.

Supported Platforms

  • Linux (amd64, arm64)
  • macOS (amd64, arm64)

References

License

See LICENSE file.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors