加载多个gojsonschemas供以后使用

问题描述 投票:0回答:1

我正在尝试为我的其余API管理json验证。我决定使用github.com/xeipuuv/gojsonschema包实现。

func (a Auth) Login(w http.ResponseWriter, r *http.Request) {

    bodyBytes, err := ioutil.ReadAll(r.Body)
    if err != nil {
        w.WriteHeader(http.StatusBadRequest)
        return
    }

    cwd, _ := os.Getwd()
    src := "file://" + cwd + "/schemas/auth.json"

    schemaLoader := gojsonschema.NewReferenceLoader(src)
    ...

以上工作正常,但我不高兴,因为对于每个API请求,都需要加载架构。

所以在我的应用程序设置中,我想将所有模式加载到模式映射中以供以后使用。

package schemas

import (
    "os"
    "path/filepath"
    "strings"

    "github.com/xeipuuv/gojsonschema"
)

const ext = ".json"

func LoadSchemas() error {
    pathS, err := os.Getwd()
    if err != nil {
        return err
    }

    var files = make(map[string]*gojsonschema.jsonReferenceLoader) // This is where I am stuck...
    filepath.Walk(pathS+"/schemas", func(path string, f os.FileInfo, _ error) error {
        if !f.IsDir() {
            if filepath.Ext(path) == ext {
                key := strings.TrimRight(f.Name(), ext)
                files[key] = gojsonschema.NewReferenceLoader("file://" + path)
            }
        }
        return nil
    })

    return nil
}

gojsonschema.NewReferenceLoader("file://" + path)返回*jsonReferenceLoader - jsonReferenceLoader不会导出到包外。

// NewReferenceLoader returns a JSON reference loader using the given source and the local OS file system.
func NewReferenceLoader(source string) *jsonReferenceLoader {
    return &jsonReferenceLoader{
        fs:     osFS,
        source: source,
    }
}

有关如何解决上述问题的任何提示/技巧?

go jsonschema
1个回答
1
投票

从@ marc的回复中,您只需使用JSONLoader界面:

var files = make(map[string]gojsonschema.JSONLoader)

在Go中,任何变量/类型/函数/等。以小写字母开头的是“私有”,因此在该包之外不可见。由于您的代码不是gojsonschema包的一部分,因此您无法访问该类型。

这是Go Tour中的一个例子:https://tour.golang.org/basics/3

© www.soinside.com 2019 - 2024. All rights reserved.