-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
70 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
package cmd | ||
|
||
import ( | ||
"fmt" | ||
|
||
"github.com/spf13/cobra" | ||
"github.com/spf13/viper" | ||
|
||
"github.com/divergentcodes/jwt-block/internal/core" | ||
"github.com/divergentcodes/jwt-block/web" | ||
) | ||
|
||
var openapiCmd = &cobra.Command{ | ||
Use: "openapi", | ||
Short: "Generate OpenAPI specs for jwt-block", | ||
Long: "Generate OpenAPI specs for jwt-block", | ||
Run: openapi, | ||
} | ||
|
||
func init() { | ||
openapiCmd.PersistentFlags().String("format", "yaml", "A string flag with limited values (value1, value2)") | ||
viper.BindPFlag("format", openapiCmd.PersistentFlags().Lookup("format")) | ||
|
||
rootCmd.AddCommand(openapiCmd) | ||
} | ||
|
||
func openapi(cmd *cobra.Command, args []string) { | ||
logger := core.GetLogger() | ||
|
||
format := viper.GetString("format") | ||
schema, err := web.GenerateOpenAPI(format) | ||
if err != nil { | ||
logger.Fatalw(err.Error()) | ||
} | ||
|
||
fmt.Print(schema) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
package web | ||
|
||
import ( | ||
"fmt" | ||
|
||
"github.com/swaggest/openapi-go/openapi3" | ||
) | ||
|
||
// Generate the OpenAPI spec for the service. | ||
func GenerateOpenAPI(format string) (string, error) { | ||
reflector := openapi3.Reflector{} | ||
|
||
// Declare security scheme. | ||
securityName := "bearer_token" | ||
reflector.SpecEns().SetHTTPBearerTokenSecurity(securityName, "JWT", "Admin Access") | ||
|
||
// Endpoints | ||
blockGenerateOpenAPI(&reflector) | ||
|
||
var schema []byte | ||
var err error | ||
if format == "json" { | ||
schema, err = reflector.Spec.MarshalJSON() | ||
} else if format == "yaml" { | ||
schema, err = reflector.Spec.MarshalYAML() | ||
} else { | ||
return "", fmt.Errorf("invalid OpenAPI output format: %s", format) | ||
} | ||
if err != nil { | ||
return "", err | ||
} | ||
return string(schema), nil | ||
} |