Skip to content

Commit aeec0c7

Browse files
committed
Ability to go embed schema
Fixes: #8 Signed-off-by: נυαη נυαηѕση <[email protected]>
1 parent e84fc2f commit aeec0c7

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

openapi.go

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,15 @@ type Config struct {
2525
// Required.
2626
Schema string
2727

28+
// SchemaBytes allows loading the OpenAPI specification directly
29+
// from a byte slice ([]byte). This is useful for embedding the
30+
// OpenAPI spec in the binary using Go's embed package, or if the
31+
// spec is obtained dynamically at runtime.
32+
// Required unless Schema is provided.
33+
//
34+
// If both Schema and SchemaBytes are provided, SchemaBytes takes precedence.
35+
SchemaBytes []byte
36+
2837
// ContextKey defines the key that will be used to store the validator
2938
// on the echo.Context when the request is successfully validated.
3039
// Optional. Defaults to "validator".
@@ -46,13 +55,19 @@ func OpenAPI(file string) echo.MiddlewareFunc {
4655
return OpenAPIWithConfig(c)
4756
}
4857

58+
func OpenAPIFromBytes(schemaBytes []byte) echo.MiddlewareFunc {
59+
c := DefaultConfig
60+
c.SchemaBytes = schemaBytes
61+
return OpenAPIWithConfig(c)
62+
}
63+
4964
func OpenAPIWithConfig(config Config) echo.MiddlewareFunc {
5065
if config.Skipper == nil {
5166
config.Skipper = DefaultConfig.Skipper
5267
}
5368

54-
if config.Schema == "" {
55-
panic("schema is required")
69+
if config.Schema == "" && len(config.SchemaBytes) == 0 {
70+
panic("either schema or schemaBytes is required")
5671
}
5772

5873
if config.ContextKey == "" {
@@ -61,7 +76,16 @@ func OpenAPIWithConfig(config Config) echo.MiddlewareFunc {
6176

6277
ctx := context.Background()
6378
loader := &openapi3.Loader{Context: ctx, IsExternalRefsAllowed: true}
64-
schema, err := loader.LoadFromFile(config.Schema)
79+
80+
var schema *openapi3.T
81+
var err error
82+
83+
if len(config.SchemaBytes) > 0 {
84+
schema, err = loader.LoadFromData(config.SchemaBytes)
85+
} else {
86+
schema, err = loader.LoadFromFile(config.Schema)
87+
}
88+
6589
if err != nil {
6690
panic(fmt.Sprintf("failed loading schema file: %v", err))
6791
}

0 commit comments

Comments
 (0)