Skip to content

0xbytejay/go-zero-swagger-ui

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

go-zero-swagger-ui

go-zero-swagger-ui is a simple Go package designed to integrate Swagger UI into Go projects. It allows you to serve Swagger UI documentation by reading a Swagger JSON file and providing the necessary file system to load Swagger UI.

This package is intended to be used with Swagger JSON files generated by the goctl-swagger tool.

Features

  • Serve Swagger UI from a Swagger JSON file.

Installation

Use Go Modules to manage dependencies. Install the package by running the following command:

go get github.com/0xbytejay/go-zero-swagger-ui@v0.1.0

Usage

  1. Generate Swagger JSON with goctl-swagger

First, generate the Swagger JSON file using the goctl-swagger tool. This is usually done from your Go source code that has API annotations.

goctl api plugin -p goctl-swagger="swagger -filename swagger.json" --api backend.api --dir .

This will generate a swagger.json file, which you will later use with go-zero-swagger-ui.

  1. Initialize Swagger UI Configuration

Next, provide the path to the generated Swagger JSON file. Use the FromJson function to load the file and generate the required Swagger UI files.

package main

import (
	"flag"
	"fmt"
	"github.com/0xbytejay/go-zero-swagger-ui"
	swaggerFiles "github.com/swaggo/files"
	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/rest"
	"go_zero_demo/internal/config"
	"go_zero_demo/internal/handler"
	"go_zero_demo/internal/svc"
)

var configFile = flag.String("f", "etc/backend-api.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)
	
	err := GoZeroSwaggerUI.FromJson("swagger.json")
	if err != nil {
		panic(err)
	}

	swaggerFiles.NewHandler()
	server := rest.MustNewServer(c.RestConf, rest.WithFileServer("/swagger/", GoZeroSwaggerUI.FileSystem()))
	defer server.Stop()

	ctx := svc.NewServiceContext(c)
	handler.RegisterHandlers(server, ctx)

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}
  1. Access Swagger UI

Once the server is running, visit http://localhost:8888/swagger/ to see the integrated Swagger UI.

Contributing

If you find any bugs or have suggestions for improvements, feel free to open an Issue or submit a Pull Request.

License

MIT License. See LICENSE for more details.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages