70 lines
1.5 KiB
Go
70 lines
1.5 KiB
Go
package apigen
|
|
|
|
import (
|
|
"errors"
|
|
apierrors "git.yuntuo.hk/k2safe/go-omni/errors"
|
|
"git.yuntuo.hk/k2safe/go-omni/response"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
)
|
|
|
|
const catalogDocumentFile = "omni.errors.json"
|
|
|
|
func readDocumentCatalog(root string, spec *Spec) error {
|
|
path := filepath.Join(root, catalogDocumentFile)
|
|
stat, err := os.Lstat(path)
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !stat.Mode().IsRegular() {
|
|
return errors.New("api: error metadata must be a regular file")
|
|
}
|
|
file, err := os.Open(path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer file.Close()
|
|
raw, err := io.ReadAll(io.LimitReader(file, (1<<20)+1))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if len(raw) > 1<<20 {
|
|
return errors.New("api: error metadata exceeds 1 MiB")
|
|
}
|
|
var catalog apierrors.Catalog
|
|
if err = apierrors.DecodeCatalogJSON(raw, &catalog); err != nil {
|
|
return err
|
|
}
|
|
registry, err := apierrors.NewRegistry(catalog)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
normalized := registry.Catalog()
|
|
spec.DocumentCatalog = &normalized
|
|
spec.Sources[catalogDocumentFile] = raw
|
|
spec.SourcePaths[catalogDocumentFile] = path
|
|
return nil
|
|
}
|
|
func validateDocumentCatalog(spec *Spec) error {
|
|
if spec.DocumentCatalog == nil {
|
|
return nil
|
|
}
|
|
for _, r := range spec.Routes {
|
|
if len(r.Errors) > 0 {
|
|
continue
|
|
}
|
|
policy, err := response.New(responseConfig(spec, r))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err = policy.ValidateErrors(*spec.DocumentCatalog); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|