### Quick Start: Basic Gin OpenAPI Setup Source: https://github.com/oaswrap/spec/blob/main/adapter/ginopenapi/README.md Demonstrates setting up a Gin server with ginopenapi, defining routes with OpenAPI options, and starting the server. Includes example request/response structs and middleware. ```go package main import ( "log" "github.com/gin-gonic/gin" "github.com/oaswrap/spec/adapter/ginopenapi" "github.com/oaswrap/spec/option" ) func main() { e := gin.Default() // Create a new OpenAPI router r := ginopenapi.NewRouter(e, option.WithTitle("My API"), option.WithVersion("1.0.0"), option.WithSecurity("bearerAuth", option.SecurityHTTPBearer("Bearer")), ) // Add routes v1 := r.Group("/api/v1") v1.POST("/login", LoginHandler).With( option.Summary("User login"), option.Request(new(LoginRequest)), option.Response(200, new(LoginResponse)), ) auth := v1.Group("/", AuthMiddleware).With( option.GroupSecurity("bearerAuth"), ) auth.GET("/users/:id", GetUserHandler).With( option.Summary("Get user by ID"), option.Request(new(GetUserRequest)), option.Response(200, new(User)), ) log.Printf("🚀 OpenAPI docs available at: %s", "http://localhost:3000/docs") if err := e.Run(":3000"); err != nil { log.Fatal(err) } } type LoginRequest struct { Username string `json:"username" required:"true"` Password string `json:"password" required:"true"` } type LoginResponse struct { Token string `json:"token"` } type GetUserRequest struct { ID string `path:"id" uri:"id" required:"true"` } type User struct { ID string `json:"id"` Name string `json:"name"` } func AuthMiddleware(c *gin.Context) { authHeader := c.GetHeader("Authorization") if authHeader != "" && authHeader == "Bearer example-token" { c.Next() } else { c.JSON(401, gin.H{"error": "Unauthorized"}) c.Abort() } } func LoginHandler(c *gin.Context) { var req LoginRequest if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, map[string]string{"error": "Invalid request"}) return } // Simulate login logic c.JSON(200, LoginResponse{Token: "example-token"}) } func GetUserHandler(c *gin.Context) { var req GetUserRequest if err := c.ShouldBindUri(&req); err != nil { c.JSON(400, map[string]string{"error": "Invalid request"}) return } // Simulate fetching user by ID user := User{ID: req.ID, Name: "John Doe"} c.JSON(200, user) } ``` -------------------------------- ### Quick Start: Fiber OpenAPI Setup Source: https://github.com/oaswrap/spec/blob/main/adapter/fiberopenapi/README.md Demonstrates setting up a Fiber app with the fiberopenapi router, defining routes with options, and starting the server. Includes example request/response types and middleware. ```go package main import ( "log" "github.com/gofiber/fiber/v2" "github.com/oaswrap/spec/adapter/fiberopenapi" "github.com/oaswrap/spec/option" ) func main() { app := fiber.New() // Create a new OpenAPI router r := fiberopenapi.NewRouter(app, option.WithTitle("My API"), option.WithVersion("1.0.0"), option.WithSecurity("bearerAuth", option.SecurityHTTPBearer("Bearer")), ) // Add routes v1 := r.Group("/api/v1") v1.Post("/login", LoginHandler).With( option.Summary("User login"), option.Request(new(LoginRequest)), option.Response(200, new(LoginResponse)), ) auth := v1.Group("/", AuthMiddleware).With( option.GroupSecurity("bearerAuth"), ) auth.Get("/users/:id", GetUserHandler).With( option.Summary("Get user by ID"), option.Request(new(GetUserRequest)), option.Response(200, new(User)), ) log.Printf("🚀 OpenAPI docs available at: %s", "http://localhost:3000/docs") if err := app.Listen(":3000"); err != nil { log.Fatal(err) } } type LoginRequest struct { Username string `json:"username" required:"true"` Password string `json:"password" required:"true"` } type LoginResponse struct { Token string `json:"token"` } type GetUserRequest struct { ID string `params:"id" required:"true"` } type User struct { ID string `json:"id"` Name string `json:"name"` } func AuthMiddleware(c *fiber.Ctx) error { authHeader := c.Get("Authorization") if authHeader != "" && authHeader == "Bearer example-token" { return c.Next() } return c.Status(401).JSON(map[string]string{"error": "Unauthorized"}) } func LoginHandler(c *fiber.Ctx) error { var req LoginRequest if err := c.BodyParser(&req); err != nil { return c.Status(400).JSON(map[string]string{"error": "Invalid request"}) } // Simulate login logic return c.Status(200).JSON(LoginResponse{Token: "example-token"}) } func GetUserHandler(c *fiber.Ctx) error { var req GetUserRequest if err := c.ParamsParser(&req); err != nil { return c.Status(400).JSON(map[string]string{"error": "Invalid request"}) } // Simulate fetching user by ID user := User{ID: req.ID, Name: "John Doe"} return c.Status(200).JSON(user) } ``` -------------------------------- ### Quick Start: Basic API Setup Source: https://github.com/oaswrap/spec/blob/main/adapter/httpopenapi/README.md Demonstrates setting up a basic API with routes, request/response definitions, and middleware using the httpopenapi adapter. Includes server startup and logging. ```go package main import ( "encoding/json" "log" "net/http" "time" "github.com/oaswrap/spec/adapter/httpopenapi" "github.com/oaswrap/spec/option" ) func main() { mainMux := http.NewServeMux() r := httpopenapi.NewGenerator(mainMux, option.WithTitle("My API"), option.WithVersion("1.0.0"), option.WithSecurity("bearerAuth", option.SecurityHTTPBearer("Bearer")), ) r.Route("/api/v1", func(r httpopenapi.Router) { r.HandleFunc("POST /login", LoginHandler).With( option.Summary("User login"), option.Request(new(LoginRequest)), option.Response(200, new(LoginResponse)), ) auth := r.Group("/", AuthMiddleware).With( option.GroupSecurity("bearerAuth"), ) auth.HandleFunc("GET /users/{id}", GetUserHandler).With( option.Summary("Get user by ID"), option.Request(new(GetUserRequest)), option.Response(200, new(User)), ) }) log.Printf("🚀 OpenAPI docs available at: %s", "http://localhost:3000/docs") // Start the server server := &http.Server{ Handler: mainMux, Addr: ":3000", ReadHeaderTimeout: 5 * time.Second, } if err := server.ListenAndServe(); err != nil { log.Fatal(err) } } type LoginRequest struct { Username string `json:"username" required:"true"` Password string `json:"password" required:"true"` } type LoginResponse struct { Token string `json:"token"` } type GetUserRequest struct { ID string `path:"id" required:"true"` } type User struct { ID string `json:"id"` Name string `json:"name"` } func AuthMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Simulate authentication logic authHeader := r.Header.Get("Authorization") if authHeader != "" && authHeader == "Bearer example-token" { next.ServeHTTP(w, r) } else { http.Error(w, "Unauthorized", http.StatusUnauthorized) } }) } func LoginHandler(w http.ResponseWriter, r *http.Request) { var req LoginRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, "Invalid request", http.StatusBadRequest) return } // Simulate login logic _ = json.NewEncoder(w).Encode(LoginResponse{Token: "example-token"}) } func GetUserHandler(w http.ResponseWriter, r *http.Request) { var req GetUserRequest id := r.PathValue("id") if id == "" { http.Error(w, "User ID is required", http.StatusBadRequest) return } req.ID = id // Simulate fetching user by ID user := User{ID: req.ID, Name: "John Doe"} _ = json.NewEncoder(w).Encode(user) } ``` -------------------------------- ### Quick Start: Echo OpenAPI Integration Source: https://github.com/oaswrap/spec/blob/main/adapter/echoopenapi/README.MD Demonstrates setting up an Echo server with the echoopenapi adapter, defining routes with options, and starting the server. Includes example request/response structs and middleware. ```go package main import ( "log" "github.com/labstack/echo/v4" "github.com/oaswrap/spec/adapter/echoopenapi" "github.com/oaswrap/spec/option" ) func main() { e := echo.New() // Create a new OpenAPI router r := echoopenapi.NewRouter(e, option.WithTitle("My API"), option.WithVersion("1.0.0"), option.WithSecurity("bearerAuth", option.SecurityHTTPBearer("Bearer")), ) // Add routes v1 := r.Group("/api/v1") v1.POST("/login", LoginHandler).With( option.Summary("User login"), option.Request(new(LoginRequest)), option.Response(200, new(LoginResponse)), ) auth := v1.Group("", AuthMiddleware).With( option.GroupSecurity("bearerAuth"), ) auth.GET("/users/:id", GetUserHandler).With( option.Summary("Get user by ID"), option.Request(new(GetUserRequest)), option.Response(200, new(User)), ) log.Printf("🚀 OpenAPI docs available at: %s", "http://localhost:3000/docs") if err := e.Start(":3000"); err != nil { log.Fatal(err) } } type LoginRequest struct { Username string `json:"username" required:"true"` Password string `json:"password" required:"true"` } type LoginResponse struct { Token string `json:"token"` } type GetUserRequest struct { ID string `param:"id" required:"true"` } type User struct { ID string `json:"id"` Name string `json:"name"` } func AuthMiddleware(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { // Simulate authentication logic authHeader := c.Request().Header.Get("Authorization") if authHeader != "" && authHeader == "Bearer example-token" { return next(c) } return c.JSON(401, map[string]string{"error": "Unauthorized"}) } } func LoginHandler(c echo.Context) error { var req LoginRequest if err := c.Bind(&req); err != nil { return c.JSON(400, map[string]string{"error": "Invalid request"}) } // Simulate login logic return c.JSON(200, LoginResponse{Token: "example-token"}) } func GetUserHandler(c echo.Context) error { var req GetUserRequest if err := c.Bind(&req); err != nil { return c.JSON(400, map[string]string{"error": "Invalid request"}) } // Simulate fetching user by ID user := User{ID: req.ID, Name: "John Doe"} return c.JSON(200, user) } ``` -------------------------------- ### Install fiberopenapi Adapter Source: https://github.com/oaswrap/spec/blob/main/adapter/fiberopenapi/README.md Install the fiberopenapi adapter using go get. ```bash go get github.com/oaswrap/spec/adapter/fiberopenapi ``` -------------------------------- ### Install httpopenapi Adapter Source: https://github.com/oaswrap/spec/blob/main/adapter/httpopenapi/README.md Install the httpopenapi adapter using the go get command. ```bash go get github.com/oaswrap/spec/adapter/httpopenapi ``` -------------------------------- ### Install ginopenapi Source: https://github.com/oaswrap/spec/blob/main/adapter/ginopenapi/README.md Use go get to install the ginopenapi package. ```bash go get github.com/oaswrap/spec/adapter/ginopenapi ``` -------------------------------- ### Install muxopenapi Adapter Source: https://github.com/oaswrap/spec/blob/main/adapter/muxopenapi/README.md Install the muxopenapi adapter using go get. ```bash go get github.com/oaswrap/spec/adapter/muxopenapi ``` -------------------------------- ### Iris OpenAPI Quick Start Example Source: https://github.com/oaswrap/spec/blob/main/adapter/irisopenapi/README.md A basic example demonstrating how to set up an Iris application with the irisopenapi adapter, define a route, and configure OpenAPI options. ```go package main import ( "github.com/kataras/iris/v12" "github.com/oaswrap/spec/adapter/irisopenapi" "github.com/oaswrap/spec/option" ) func main() { app := iris.New() r := irisopenapi.NewRouter(app, option.WithTitle("My API"), option.WithVersion("1.0.0"), ) r.Get("/ping", func(ctx iris.Context) { _ = ctx.JSON(map[string]string{"message": "pong"}) }).With( option.OperationID("ping"), option.Response(200, new(struct { Message string `json:"message"` })), ) _ = app.Listen(":8080") } ``` -------------------------------- ### Install irisopenapi Adapter Source: https://github.com/oaswrap/spec/blob/main/adapter/irisopenapi/README.md Install the irisopenapi adapter using go get. ```bash go get github.com/oaswrap/spec/adapter/irisopenapi ``` -------------------------------- ### Install echov5openapi Adapter Source: https://github.com/oaswrap/spec/blob/main/adapter/echov5openapi/README.MD Use 'go get' to install the echov5openapi adapter for your Go project. ```bash go get github.com/oaswrap/spec/adapter/echov5openapi ``` -------------------------------- ### Quick Start: Chi OpenAPI Router Setup Source: https://github.com/oaswrap/spec/blob/main/adapter/chiopenapi/README.md Demonstrates setting up a Chi router with the chiopenapi adapter, defining routes, and applying OpenAPI options like title, version, and security. ```go package main import ( "encoding/json" "log" "net/http" "time" "github.com/go-chi/chi/v5" "github.com/oaswrap/spec/adapter/chiopenapi" "github.com/oaswrap/spec/option" ) func main() { c := chi.NewRouter() // Create a new OpenAPI router r := chiopenapi.NewRouter(c, option.WithTitle("My API"), option.WithVersion("1.0.0"), option.WithSecurity("bearerAuth", option.SecurityHTTPBearer("Bearer")), ) // Add routes r.Route("/api/v1", func(r chiopenapi.Router) { r.Post("/login", LoginHandler).With( option.Summary("User login"), option.Request(new(LoginRequest)), option.Response(200, new(LoginResponse)), ) r.Group(func(r chiopenapi.Router) { r.Use(AuthMiddleware) r.Get("/users/{id}", GetUserHandler).With( option.Summary("Get user by ID"), option.Request(new(GetUserRequest)), option.Response(200, new(User)), ) }, option.GroupSecurity("bearerAuth") ) }) log.Printf("🚀 OpenAPI docs available at: %s", "http://localhost:3000/docs") // Start the server server := &http.Server{ Handler: c, Addr: ":3000", ReadHeaderTimeout: 5 * time.Second, } if err := server.ListenAndServe(); err != nil { log.Fatal(err) } } type LoginRequest struct { Username string `json:"username" required:"true"` Password string `json:"password" required:"true"` } type LoginResponse struct { Token string `json:"token"` } type GetUserRequest struct { ID string `path:"id" required:"true"` } type User struct { ID string `json:"id"` Name string `json:"name"` } func AuthMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Simulate authentication logic authHeader := r.Header.Get("Authorization") if authHeader != "" && authHeader == "Bearer example-token" { next.ServeHTTP(w, r) } else { http.Error(w, "Unauthorized", http.StatusUnauthorized) } }) } func LoginHandler(w http.ResponseWriter, r *http.Request) { var req LoginRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, "Invalid request", http.StatusBadRequest) return } // Simulate login logic _ = json.NewEncoder(w).Encode(LoginResponse{Token: "example-token"}) } func GetUserHandler(w http.ResponseWriter, r *http.Request) { var req GetUserRequest id := chi.URLParam(r, "id") if id == "" { http.Error(w, "User ID is required", http.StatusBadRequest) return } req.ID = id // Simulate fetching user by ID user := User{ID: req.ID, Name: "John Doe"} _ = json.NewEncoder(w).Encode(user) } ``` -------------------------------- ### Install oaswrap/spec Source: https://github.com/oaswrap/spec/blob/main/README.md Install the oaswrap/spec package using go get. Ensure you have Go 1.22+ installed. ```bash go get -u github.com/oaswrap/spec ``` -------------------------------- ### Quick Start: Fiber v3 OpenAPI Integration Source: https://github.com/oaswrap/spec/blob/main/adapter/fiberv3openapi/README.md Demonstrates setting up a Fiber v3 application with the OpenAPI adapter. It shows how to create a router, define routes with OpenAPI options, and start the server. Ensure to define your request and response structs. ```go package main import ( "log" "github.com/gofiber/fiber/v3" "github.com/oaswrap/spec/adapter/fiberv3openapi" "github.com/oaswrap/spec/option" ) func main() { app := fiber.New() // Create a new OpenAPI router r := fiberv3openapi.NewRouter(app, option.WithTitle("My API"), option.WithVersion("1.0.0"), option.WithSecurity("bearerAuth", option.SecurityHTTPBearer("Bearer")), ) // Add routes v1 := r.Group("/api/v1") v1.Post("/login", LoginHandler).With( option.Summary("User login"), option.Request(new(LoginRequest)), option.Response(200, new(LoginResponse)), ) auth := v1.Group("/", AuthMiddleware).With( option.GroupSecurity("bearerAuth"), ) auth.Get("/users/:id", GetUserHandler).With( option.Summary("Get user by ID"), option.Request(new(GetUserRequest)), option.Response(200, new(User)), ) log.Printf("🚀 OpenAPI docs available at: %s", "http://localhost:3000/docs") if err := app.Listen(":3000"); err != nil { log.Fatal(err) } } type LoginRequest struct { Username string `json:"username" required:"true"` Password string `json:"password" required:"true"` } type LoginResponse struct { Token string `json:"token"` } type GetUserRequest struct { ID string `uri:"id" required:"true"` } type User struct { ID string `json:"id"` Name string `json:"name"` } func AuthMiddleware(c fiber.Ctx) error { authHeader := c.Get("Authorization") if authHeader != "" && authHeader == "Bearer example-token" { return c.Next() } return c.Status(401).JSON(map[string]string{"error": "Unauthorized"}) } func LoginHandler(c fiber.Ctx) error { var req LoginRequest if err := c.Bind().Body(&req); err != nil { return c.Status(400).JSON(map[string]string{"error": "Invalid request"}) } return c.Status(200).JSON(LoginResponse{Token: "example-token"}) } func GetUserHandler(c fiber.Ctx) error { var req GetUserRequest if err := c.Bind().URI(&req); err != nil { return c.Status(400).JSON(map[string]string{"error": "Invalid request"}) } user := User{ID: req.ID, Name: "John Doe"} return c.Status(200).JSON(user) } ``` -------------------------------- ### Install echoopenapi Adapter Source: https://github.com/oaswrap/spec/blob/main/adapter/echoopenapi/README.MD Use go get to install the echoopenapi adapter for your Go project. ```bash go get github.com/oaswrap/spec/adapter/echoopenapi ``` -------------------------------- ### Install Release Tools Source: https://github.com/oaswrap/spec/blob/main/RELEASE.md Installs the necessary tools for the release process. Run this before starting any release steps. ```bash make install-tools ``` -------------------------------- ### Quick Start: Echo v5 with echov5openapi Source: https://github.com/oaswrap/spec/blob/main/adapter/echov5openapi/README.MD Demonstrates setting up an Echo v5 server with the echov5openapi adapter to define routes, apply options like title and version, and serve OpenAPI documentation. ```go package main import ( "log" "github.com/labstack/echo/v5" "github.com/oaswrap/spec/adapter/echov5openapi" "github.com/oaswrap/spec/option" ) func main() { e := echo.New() // Create a new OpenAPI router r := echov5openapi.NewRouter(e, option.WithTitle("My API"), option.WithVersion("1.0.0"), option.WithSecurity("bearerAuth", option.SecurityHTTPBearer("Bearer")), ) // Add routes v1 := r.Group("/api/v1") v1.POST("/login", LoginHandler).With( option.Summary("User login"), option.Request(new(LoginRequest)), option.Response(200, new(LoginResponse)), ) auth := v1.Group("", AuthMiddleware).With( option.GroupSecurity("bearerAuth"), ) auth.GET("/users/:id", GetUserHandler).With( option.Summary("Get user by ID"), option.Request(new(GetUserRequest)), option.Response(200, new(User)), ) log.Printf("OpenAPI docs available at: %s", "http://localhost:3000/docs") if err := e.Start(":3000"); err != nil { log.Fatal(err) } } type LoginRequest struct { Username string `json:"username" required:"true"` Password string `json:"password" required:"true"` } type LoginResponse struct { Token string `json:"token"` } type GetUserRequest struct { ID string `param:"id" required:"true"` } type User struct { ID string `json:"id"` Name string `json:"name"` } // Note: Echo v5 uses *echo.Context instead of echo.Context func AuthMiddleware(next echo.HandlerFunc) echo.HandlerFunc { return func(c *echo.Context) error { // Simulate authentication logic authHeader := c.Request().Header.Get("Authorization") if authHeader != "" && authHeader == "Bearer example-token" { return next(c) } return c.JSON(401, map[string]string{"error": "Unauthorized"}) } } func LoginHandler(c *echo.Context) error { var req LoginRequest if err := c.Bind(&req); err != nil { return c.JSON(400, map[string]string{"error": "Invalid request"}) } // Simulate login logic return c.JSON(200, LoginResponse{Token: "example-token"}) } func GetUserHandler(c *echo.Context) error { var req GetUserRequest if err := c.Bind(&req); err != nil { return c.JSON(400, map[string]string{"error": "Invalid request"}) } // Simulate fetching user by ID user := User{ID: req.ID, Name: "John Doe"} return c.JSON(200, user) } ``` -------------------------------- ### Quick Start: Initialize Router and Define Routes Source: https://github.com/oaswrap/spec/blob/main/adapter/muxopenapi/README.md Initialize a new muxopenapi router with options and define API routes with request/response schemas and security. ```go package main import ( "encoding/json" "log" "net/http" "time" "github.com/gorilla/mux" "github.com/oaswrap/spec/adapter/muxopenapi" "github.com/oaswrap/spec/option" ) func main() { mux := mux.NewRouter() r := muxopenapi.NewRouter(mux, option.WithTitle("My API"), option.WithVersion("1.0.0"), option.WithSecurity("bearerAuth", option.SecurityHTTPBearer("Bearer")), ) api := r.PathPrefix("/api").Subrouter() v1 := api.PathPrefix("/v1").Subrouter() v1.HandleFunc("/login", LoginHandler).Methods("POST").With( option.Summary("User Login"), option.Request(new(LoginRequest)), option.Response(200, new(LoginResponse)), ) auth := v1.PathPrefix("/").Subrouter().With( option.GroupSecurity("bearerAuth"), ) auth.Use(AuthMiddleware) auth.HandleFunc("/users/{id}", GetUserHandler).Methods("GET").With( option.Summary("Get User by ID"), option.Request(new(GetUserRequest)), option.Response(200, new(User)), ) log.Printf("🚀 OpenAPI docs available at: %s", "http://localhost:3000/docs") // Start the server server := &http.Server{ Handler: mux, Addr: ":3000", ReadHeaderTimeout: 5 * time.Second, } if err := server.ListenAndServe(); err != nil { log.Fatal(err) } } type LoginRequest struct { Username string `json:"username" required:"true"` Password string `json:"password" required:"true"` } type LoginResponse struct { Token string `json:"token"` } type GetUserRequest struct { ID string `path:"id" required:"true"` } type User struct { ID string `json:"id"` Name string `json:"name"` } func AuthMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Simulate authentication logic authHeader := r.Header.Get("Authorization") if authHeader != "" && authHeader == "Bearer example-token" { next.ServeHTTP(w, r) } else { http.Error(w, "Unauthorized", http.StatusUnauthorized) } }) } func LoginHandler(w http.ResponseWriter, r *http.Request) { var req LoginRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, "Invalid request", http.StatusBadRequest) return } // Simulate login logic _ = json.NewEncoder(w).Encode(LoginResponse{Token: "example-token"}) } func GetUserHandler(w http.ResponseWriter, r *http.Request) { var req GetUserRequest vars := mux.Vars(r) id := vars["id"] if id == "" { http.Error(w, "User ID is required", http.StatusBadRequest) return } req.ID = id // Simulate fetching user by ID user := User{ID: req.ID, Name: "John Doe"} _ = json.NewEncoder(w).Encode(user) } ``` -------------------------------- ### Quick Start: Build OpenAPI Schema Source: https://github.com/oaswrap/spec/blob/main/README.md Demonstrates how to initialize a router, define API routes with options for summary, request/response types, and security, and then write the generated OpenAPI schema to a file. This example uses OpenAPI version 3.2.0. ```go package main import ( "log" "github.com/oaswrap/spec" "github.com/oaswrap/spec/openapi" "github.com/oaswrap/spec/option" ) func main() { r := spec.NewRouter( option.WithOpenAPIVersion(openapi.Version320), option.WithTitle("Users API"), option.WithVersion("1.0.0"), option.WithServer("https://api.example.com"), option.WithSecurity("bearerAuth", option.SecurityHTTPBearer("bearer")), ) v1 := r.Group("/api/v1", option.GroupTags("users")) v1.Post("/login", option.Summary("Login"), option.Request(new(LoginRequest)), option.Response(200, new(LoginResponse)), ) v1.Get("/users/{id}", option.Summary("Get user"), option.Request(new(GetUserRequest)), option.Response(200, new(User)), ) if err := r.WriteSchemaTo("openapi.yaml"); err != nil { log.Fatal(err) } } type LoginRequest struct { Username string `json:"username" required:"true"` Password string `json:"password" required:"true" writeOnly:"true"` } type LoginResponse struct { Token string `json:"token" required:"true"` } type GetUserRequest struct { ID string `path:"id" required:"true" description:"User identifier"` } type User struct { ID string `json:"id" required:"true"` Name string `json:"name"` } ``` -------------------------------- ### Install Fiber v3 OpenAPI Adapter Source: https://github.com/oaswrap/spec/blob/main/adapter/fiberv3openapi/README.md Use go get to install the fiberv3openapi adapter. This command fetches and installs the package, making it available for use in your Go projects. ```bash go get github.com/oaswrap/spec/adapter/fiberv3openapi ``` -------------------------------- ### Install chiopenapi Adapter Source: https://github.com/oaswrap/spec/blob/main/adapter/chiopenapi/README.md Install the chiopenapi adapter using the Go modules command. ```bash go get github.com/oaswrap/spec/adapter/chiopenapi ``` -------------------------------- ### Install Development Tools Source: https://github.com/oaswrap/spec/blob/main/CLAUDE.md Install necessary development tools, such as golangci-lint. This is a prerequisite for certain development tasks. ```bash # Install dev tools (golangci-lint) make install-tools ``` -------------------------------- ### Clone Repository and Install Tools Source: https://github.com/oaswrap/spec/blob/main/CONTRIBUTING.md Clone the oaswrap/spec repository and install necessary development tools like golangci-lint. ```bash git clone https://github.com/oaswrap/spec.git cd spec make install-tools ``` -------------------------------- ### Verify Setup with Make Check Source: https://github.com/oaswrap/spec/blob/main/CONTRIBUTING.md Run the 'check' make target to ensure your development environment is set up correctly. This includes syncing, tidying, linting, and testing. ```bash make check ``` -------------------------------- ### OpenAPI Router Configuration Source: https://github.com/oaswrap/spec/blob/main/README.md Configure a new router with various OpenAPI specification options. This example demonstrates setting version, title, summary, version, description, terms of service, contact, license, external docs, servers, tags, and stripping trailing slashes. ```go r := spec.NewRouter( option.WithOpenAPIVersion(openapi.Version312), option.WithTitle("Payments API"), option.WithInfoSummary("Payments API"), option.WithVersion("1.4.0"), option.WithDescription("Payment operations."), option.WithTermsOfService("https://example.com/terms"), option.WithContact(openapi.Contact{Name: "API Team", Email: "api@example.com"}), option.WithLicense(openapi.License{Name: "Apache 2.0", URL: "https://www.apache.org/licenses/LICENSE-2.0.html"}), option.WithExternalDocs("https://docs.example.com", "Full documentation"), option.WithServer("https://api.example.com", option.ServerDescription("Production")), option.WithTag("payments", option.TagDescription("Payment operations")), option.WithStripTrailingSlash(), ) ``` -------------------------------- ### Conventional Commit Message Examples Source: https://github.com/oaswrap/spec/blob/main/CONTRIBUTING.md Examples of valid commit messages following the Conventional Commits format. These illustrate the expected structure and content. ```text feat: add response header option ``` ```text fix: handle empty path group correctly ``` ```text docs: clarify WithSecurity usage in README ``` ```text test: add golden file for nested groups ``` ```text chore: sync adapter deps to v0.5.0 ``` -------------------------------- ### Reflector Configuration Options Source: https://github.com/oaswrap/spec/blob/main/README.md Configure the OpenAPI reflector with various options to customize schema generation, type mapping, and property handling. This example shows common configurations like inline references, stripping prefixes, and custom interceptors. ```go r := spec.NewRouter( option.WithReflectorConfig( option.InlineRefs(), option.StripDefNamePrefix("DTO"), option.TypeMapping(NullString{}, new(string)), option.ParameterTagMapping(openapi.ParameterInPath, "params"), option.InterceptDefName(func(t reflect.Type, defaultName string) string { return defaultName }), option.InterceptSchema(func(params openapi.InterceptSchemaParams) (stop bool, err error) { if params.Processed { params.Schema.Extensions = map[string]any{"x-go-type": params.Type.String()} } return false, nil }), option.InterceptProp(func(params openapi.InterceptPropParams) error { if params.Processed && params.Field.Tag.Get("internal") == "true" { return openapi.ErrSkipProperty } return nil }), option.RequiredPropByValidateTag(), // marks fields required when validate tag contains "required" ), ) ``` -------------------------------- ### Define API Group and Route Source: https://github.com/oaswrap/spec/blob/main/README.md Defines an API group for version 1 and a GET endpoint for retrieving a user. This snippet demonstrates setting operation IDs, summaries, descriptions, tags, security, and request/response structures. ```go api := r.Group("/api/v1", option.GroupTags("v1")) api.Get("/users/{id}", option.OperationID("getUser"), option.Summary("Get user"), option.Description("Returns one user."), option.Tags("users"), option.Security("bearerAuth"), option.Request(new(GetUserRequest)), option.Response(200, new(User), option.ContentDescription("OK")), option.Response(404, nil, option.ContentDescription("Not Found")), ) ``` -------------------------------- ### Use Scalar Documentation UI Source: https://github.com/oaswrap/spec/blob/main/adapter/chiopenapi/README.md Demonstrates how to configure the router to use the Scalar documentation UI by passing `option.WithScalar()`. ```go r := chiopenapi.NewRouter(c, option.WithTitle("My API"), option.WithVersion("1.0.0"), option.WithScalar(), // Use Scalar as the documentation UI ) ``` -------------------------------- ### Run All Tests Source: https://github.com/oaswrap/spec/blob/main/CONTRIBUTING.md Execute all tests for the core module and all adapters using the 'test' make target. ```bash make test ``` -------------------------------- ### Run a Single Adapter Test Source: https://github.com/oaswrap/spec/blob/main/CONTRIBUTING.md Run a specific test for an adapter module by navigating to its directory and using 'go test'. ```bash cd adapter/fiberopenapi && go test ./... -run TestName ``` -------------------------------- ### Minor Release Workflow - Stage 1 Source: https://github.com/oaswrap/spec/blob/main/RELEASE.md Prepares a minor release by tagging the core and syncing adapter dependencies. Includes running checks and committing sync results. ```bash # Complete development and testing make check # Update documentation (README, examples, etc.) # Run Stage 1 (core tag + dependency sync) make release-prepare VERSION=0.4.0 # Commit the sync result produced by stage 1 git add adapter/*/go.mod adapter/*/go.sum git commit -m "chore: sync adapter deps to v0.4.0" git push # Publish adapter tags (stage 2) make release-publish VERSION=0.4.0 ``` -------------------------------- ### Pre-release Testing with RC Versions Source: https://github.com/oaswrap/spec/blob/main/RELEASE.md Demonstrates the release process using release candidate (RC) versions for testing before a final release. Includes dry run, prepare, commit, and publish stages. ```bash make release-dry-run VERSION=0.4.0-rc.1 make release-prepare VERSION=0.4.0-rc.1 # Commit sync changes from stage 1 git add adapter/*/go.mod adapter/*/go.sum git commit -m "chore: sync adapter deps to v0.4.0-rc.1" git push make release-publish VERSION=0.4.0-rc.1 ``` -------------------------------- ### Use Scalar Documentation UI Source: https://github.com/oaswrap/spec/blob/main/adapter/ginopenapi/README.md Configure the router to use Scalar as the documentation UI by passing option.WithScalar() during initialization. ```go r := ginopenapi.NewRouter(e, option.WithTitle("My API"), option.WithVersion("1.0.0"), option.WithScalar(), // Use Scalar as the documentation UI ) ``` -------------------------------- ### Use Scalar Documentation UI Source: https://github.com/oaswrap/spec/blob/main/adapter/echoopenapi/README.MD Configure the router to use Scalar as the documentation UI by passing option.WithScalar() during initialization. ```go r := echoopenapi.NewRouter(e, option.WithTitle("My API"), option.WithVersion("1.0.0"), option.WithScalar(), // Use Scalar as the documentation UI ) ``` -------------------------------- ### Two-Stage Monorepo Release - Prepare Source: https://github.com/oaswrap/spec/blob/main/RELEASE.md Initiates the release process by tagging the core module and synchronizing adapter dependencies. This is Stage 1 of the recommended end-to-end flow. ```bash make release-prepare VERSION=x.y.z ``` -------------------------------- ### Run All Tests in Go Source: https://github.com/oaswrap/spec/blob/main/CLAUDE.md Execute all tests, including core and adapter tests. Use this for a comprehensive test suite run. ```bash # Run all tests (core + all adapters) make test ``` -------------------------------- ### Run Adapter Tests in Go Source: https://github.com/oaswrap/spec/blob/main/CLAUDE.md Execute only the tests for the framework adapters. This is helpful when focusing on adapter-specific changes. ```bash # Run adapter tests only make test-adapter ``` -------------------------------- ### Patch Release Workflow - Stage 1 Source: https://github.com/oaswrap/spec/blob/main/RELEASE.md Prepares a patch release by tagging the core and syncing adapter dependencies. Includes running checks and committing sync results. ```bash # Ensure everything is clean and tested make check # Update any necessary documentation # Update CHANGELOG.md if maintained # Run Stage 1 (core tag + dependency sync) make release-prepare VERSION=0.3.5 # Commit the sync result produced by stage 1 git add adapter/*/go.mod adapter/*/go.sum git commit -m "chore: sync adapter deps to v0.3.5" git push # Publish adapter tags (stage 2) make release-publish VERSION=0.3.5 ``` -------------------------------- ### Configure Documentation UI to Scalar Source: https://github.com/oaswrap/spec/blob/main/adapter/httpopenapi/README.md Customize the httpopenapi generator to use Scalar as the documentation UI by passing option.WithScalar() during initialization. ```go r := httpopenapi.NewGenerator(mainMux, option.WithTitle("My API"), option.WithVersion("1.0.0"), option.WithScalar(), // Use Scalar as the documentation UI ) ``` -------------------------------- ### Configure Router with Security Schemes Source: https://github.com/oaswrap/spec/blob/main/README.md Initializes a new router with multiple security schemes including API Key, HTTP Bearer, Mutual TLS, OAuth2, and OpenID Connect. This is used to define how clients can authenticate with the API. ```go r := spec.NewRouter( option.WithSecurity("apiKey", option.SecurityAPIKey("X-API-Key", openapi.SecurityAPIKeyInHeader)), option.WithSecurity("bearerAuth", option.SecurityHTTPBearer("bearer")), option.WithSecurity("mtls", option.SecurityMutualTLS()), option.WithSecurity("oauth2", option.SecurityOAuth2AuthorizationCode( "https://auth.example.com/oauth/authorize", "https://auth.example.com/oauth/token", map[string]string{ "read": "Read access", "write": "Write access", }, )), option.WithSecurity("oidc", option.SecurityOpenIDConnect("https://auth.example.com/.well-known/openid-configuration")), ) ``` -------------------------------- ### Run a Single Core Test Source: https://github.com/oaswrap/spec/blob/main/CONTRIBUTING.md Execute a specific test within the core module by providing its name to 'go test'. ```bash go test ./... -run TestName ``` -------------------------------- ### Run Linting Source: https://github.com/oaswrap/spec/blob/main/RELEASE.md Execute the linting process to check code quality. This command should be run before any release. ```bash # Run linting make lint ``` -------------------------------- ### Run Adapter Tests Only Source: https://github.com/oaswrap/spec/blob/main/CONTRIBUTING.md Focus on running tests specifically for the adapter modules with the 'test-adapter' make target. ```bash make test-adapter ``` -------------------------------- ### Framework Adapters Source: https://github.com/oaswrap/spec/blob/main/README.md Information on using framework-specific adapters for integrated route registration, spec generation, and UI wiring. ```APIDOC ## Framework Adapters Use the core `spec` package for static generation and CI workflows. Adapters are available for integrating OpenAPI generation directly into various web frameworks. | Framework | Package Path | |----------------|-----------------------------------------------| | Chi | `github.com/oaswrap/spec/adapter/chiopenapi` | | Echo v4 | `github.com/oaswrap/spec/adapter/echoopenapi` | | Echo v5 | `github.com/oaswrap/spec/adapter/echov5openapi`| | Fiber v2 | `github.com/oaswrap/spec/adapter/fiberopenapi`| | Fiber v3 | `github.com/oaswrap/spec/adapter/fiberv3openapi`| | Gin | `github.com/oaswrap/spec/adapter/ginopenapi` | | Iris | `github.com/oaswrap/spec/adapter/irisopenapi` | | net/http | `github.com/oaswrap/spec/adapter/httpopenapi` | | Mux | `github.com/oaswrap/spec/adapter/muxopenapi` | ``` -------------------------------- ### Run Core Tests in Go Source: https://github.com/oaswrap/spec/blob/main/CLAUDE.md Execute only the core tests for the project. This is useful for quick checks of the main functionality. ```bash # Run core tests only go test ./... ``` -------------------------------- ### Embed UI Assets for Offline Mode Source: https://github.com/oaswrap/spec/blob/main/adapter/ginopenapi/README.md Use option.WithUIOption() with the provider's emb package (e.g., stoplightemb.WithUI()) to serve embedded UI assets for offline functionality. ```go import ( stoplightemb "github.com/oaswrap/spec-ui/stoplightemb" ) // example: option.WithUIOption(stoplightemb.WithUI()) ``` -------------------------------- ### Two-Stage Monorepo Release - Publish Source: https://github.com/oaswrap/spec/blob/main/RELEASE.md Completes the release process by publishing the adapter tags. This is Stage 2 of the recommended end-to-end flow. ```bash make release-publish VERSION=x.y.z ``` -------------------------------- ### Sync Workspace Source: https://github.com/oaswrap/spec/blob/main/RELEASE.md Sync the workspace to ensure all dependencies and module states are consistent. Run this command to resolve potential workspace issues. ```bash # Sync workspace make sync ``` -------------------------------- ### Sync Adapter Dependencies Source: https://github.com/oaswrap/spec/blob/main/RELEASE.md Updates all adapter modules to reference a specified core version. The `NO_TIDY` flag can be used to skip `go mod tidy`. ```bash # Update all adapters to use the specified core version make sync-adapter-deps VERSION=v1.2.0 # Skip go mod tidy during sync (useful for CI) make sync-adapter-deps VERSION=v1.2.0 NO_TIDY=1 # Equivalent (also accepted): make sync-adapter-deps VERSION=1.2.0 make sync-adapter-deps VERSION=1.2.0 NO_TIDY=1 ``` -------------------------------- ### Run All Tests Source: https://github.com/oaswrap/spec/blob/main/RELEASE.md Execute all automated tests to ensure module health. This is a critical step before releasing. ```bash # Run all tests make test ``` -------------------------------- ### Use Scalar Documentation UI Source: https://github.com/oaswrap/spec/blob/main/adapter/fiberopenapi/README.md Customize the fiberopenapi router to use the Scalar UI for displaying OpenAPI documentation. ```go r := fiberopenapi.NewRouter(app, option.WithTitle("My API"), option.WithVersion("1.0.0"), option.WithScalar(), // Use Scalar as the documentation UI ) ``` -------------------------------- ### Update Dependencies Source: https://github.com/oaswrap/spec/blob/main/RELEASE.md Updates and tidies Go module dependencies. Run this to ensure all dependencies are up-to-date. ```bash make tidy ``` -------------------------------- ### Preview Tag Availability Source: https://github.com/oaswrap/spec/blob/main/RELEASE.md Preview tag availability before creating a release to avoid conflicts. Use this command to check if a version tag already exists. ```bash # Preview tag availability first make release-dry-run VERSION=1.2.0 ``` -------------------------------- ### Run Code Quality Checks Source: https://github.com/oaswrap/spec/blob/main/CONTRIBUTING.md Perform comprehensive code quality checks including linting, tidying, and syncing the Go workspace. ```bash make lint make tidy make sync make check ``` -------------------------------- ### Disable Built-in Documentation UI Source: https://github.com/oaswrap/spec/blob/main/adapter/ginopenapi/README.md Pass option.WithDisableDocs() during router creation to disable the automatic serving of the interactive documentation UI. ```go r := ginopenapi.NewRouter(e, option.WithTitle("My API"), option.WithVersion("1.0.0"), option.WithDisableDocs(), ) ``` -------------------------------- ### Tidy Go Modules Source: https://github.com/oaswrap/spec/blob/main/CLAUDE.md Synchronize and clean up the go.mod files for the core project and all adapters. Ensures dependency consistency. ```bash # Tidy go.mod for core + all adapters make tidy ``` -------------------------------- ### List Adapter Status Source: https://github.com/oaswrap/spec/blob/main/RELEASE.md List the status of all adapters. This command is useful for checking the health and readiness of different adapter modules. ```bash # List adapter status make list-adapters ``` -------------------------------- ### Configure OpenAPI Document with Webhooks and Extensions Source: https://github.com/oaswrap/spec/blob/main/README.md Use `WithDocument` to mutate the final OpenAPI document before output. This snippet demonstrates setting the OpenAPI version, API title and version, defining webhooks with operations and responses, and adding specification extensions and future official fields. ```go r := spec.NewRouter( option.WithOpenAPIVersion(openapi.Version320), option.WithTitle("API"), option.WithVersion("1.0.0"), option.WithDocument(func(doc *openapi.Document) { doc.Webhooks = map[string]*openapi.PathItem{ "user.created": { Post: &openapi.Operation{ Responses: map[string]*openapi.Response{ "202": {Description: "Accepted"}, }, }, }, } doc.Extensions = map[string]any{"x-company": "oaswrap"} doc.Extra = map[string]any{"futureOfficialField": true} }), ) ``` -------------------------------- ### Disable Built-in Documentation UI Source: https://github.com/oaswrap/spec/blob/main/adapter/chiopenapi/README.md Shows how to disable the automatic serving of the interactive documentation UI by passing `option.WithDisableDocs()` during router creation. ```go r := chiopenapi.NewRouter(c, option.WithTitle("My API"), option.WithVersion("1.0.0"), option.WithDisableDocs(), ) ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/oaswrap/spec/blob/main/CONTRIBUTING.md Generate test coverage information using the 'testcov' make target. ```bash make testcov ``` -------------------------------- ### Disable Built-in UI Source: https://github.com/oaswrap/spec/blob/main/adapter/echoopenapi/README.MD Pass option.WithDisableDocs() when creating the router to disable the automatic serving of the interactive UI documentation. ```go r := echoopenapi.NewRouter(e, option.WithTitle("My API"), option.WithVersion("1.0.0"), option.WithDisableDocs(), ) ``` -------------------------------- ### Resync Adapter Dependencies Source: https://github.com/oaswrap/spec/blob/main/RELEASE.md Resync adapter dependencies to resolve mismatch issues. Specify the version to resync dependencies for. ```bash # Resync dependencies make sync-adapter-deps VERSION=1.2.0 ``` -------------------------------- ### Run a Single Go Test Source: https://github.com/oaswrap/spec/blob/main/CLAUDE.md Execute a specific test case identified by a name pattern. Useful for debugging a particular test. ```bash # Run a single test go test -run TestGolden ./... ``` -------------------------------- ### Open HTML Coverage Report Source: https://github.com/oaswrap/spec/blob/main/CONTRIBUTING.md View the generated test coverage report in HTML format by running 'testcov-html'. ```bash make testcov-html ``` -------------------------------- ### Go Struct with OpenAPI Reflection Tags Source: https://github.com/oaswrap/spec/blob/main/README.md Defines a Go struct with various reflection tags to map fields to OpenAPI parameters (path, query, header, cookie) and request body properties (json, form). It also demonstrates skipping fields and setting schema constraints. ```go type SearchRequest struct { ID string `path:"id" required:"true" description:"Resource ID" Status string `query:"status" enum:"active,inactive" TraceID string `header:"X-Trace-ID" Session string `cookie:"session" Name string `json:"name" minLength:"2" maxLength:"80" File []byte `form:"file" format:"binary" description:"Upload file" Internal string `json:"-" } ``` -------------------------------- ### Migrating from Echo v4 to v5 Middleware Signatures Source: https://github.com/oaswrap/spec/blob/main/adapter/echov5openapi/README.MD Update middleware function signatures to use a pointer to echo.Context (*echo.Context) when migrating from Echo v4 to v5. ```go // Before (v4) func MyMiddleware(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { ... } } // After (v5) func MyMiddleware(next echo.HandlerFunc) echo.HandlerFunc { return func(c *echo.Context) error { ... } } ```