48 lines
1.2 KiB
Go
48 lines
1.2 KiB
Go
package openapi
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
)
|
|
|
|
// OpenAPI permits both a schema and a boolean for additionalProperties. Keep
|
|
// the existing schema field source-compatible and expose the boolean separately.
|
|
func (s Schema) MarshalJSON() ([]byte, error) {
|
|
type alias Schema
|
|
if s.AdditionalPropertiesAllowed == nil {
|
|
return json.Marshal(alias(s))
|
|
}
|
|
return json.Marshal(struct {
|
|
alias
|
|
Allowed bool `json:"additionalProperties"`
|
|
}{alias(s), *s.AdditionalPropertiesAllowed})
|
|
}
|
|
func (s *Schema) UnmarshalJSON(data []byte) error {
|
|
type alias Schema
|
|
var raw map[string]json.RawMessage
|
|
if err := json.Unmarshal(data, &raw); err != nil {
|
|
return err
|
|
}
|
|
var allowed *bool
|
|
if value, ok := raw["additionalProperties"]; ok && (string(value) == "true" || string(value) == "false") {
|
|
var v bool
|
|
_ = json.Unmarshal(value, &v)
|
|
allowed = &v
|
|
delete(raw, "additionalProperties")
|
|
var err error
|
|
data, err = json.Marshal(raw)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
var a alias
|
|
decoder := json.NewDecoder(bytes.NewReader(data))
|
|
decoder.UseNumber()
|
|
if err := decoder.Decode(&a); err != nil {
|
|
return err
|
|
}
|
|
*s = Schema(a)
|
|
s.AdditionalPropertiesAllowed = allowed
|
|
return nil
|
|
}
|