duanque19820925 2018-08-22 15:36 采纳率: 0%
浏览 30
已采纳

当作为参数传递给单独包中的函数时,Struct不是类型

I'm making a JSON validation function and I'm trying to implement it. However I'm having issues with my structs when I try to import them as a parameter to my validation function, which is in another package.

The reason to why it's in another package is because a universal validation function that I will call in different route files, so I can't actually have any structs inside that package, they must be imported and defined in the route file.

type UsersJSON struct {
    Users struct {
        Put []UserJSON `json:"PUT"`
    } `json:"users"`
}

type UserJSON struct {
    display_name     string `json:"display_name"`
    username        string `json:"username"`
    email           string `json:"email"`
    password        string `json:"password"`
}

func MyFunc(w http.ResponseWriter, r *http.Request) {
    errors, _ := schema.Validate(data, r, UsersJSON)
}

func Validate(schemaHelper interface{}) (interface{}, error) {
    file, err := os.Open("config/schema/schema.json")
    if err != nil {
        return nil, err
    }

    defer file.Close()

    byteValue, _ := ioutil.ReadAll(file)

    var helpers schemaHelper // this is the error

    json.Unmarshal(byteValue, &helpers)
    fmt.Printf("%v", helpers)
}

My JSON schema looks like this:

{
    "users": {
        "PUT": {
        }
    }
}

I want to make this method work because it makes automating validation much easier and faster.

This doesn't compile and gives the error schemaHelper is not a type

Any idea how I can solve this?

  • 写回答

2条回答 默认 最新

  • doucezhu3570 2018-08-22 15:42
    关注

    You're trying to declare a variable called helpers, of type schemaHelper, but (at least within the code shown) you have not defined any type called schemaHelper. You have a variable called schemaHelper. You can't use a type as a variable, or a variable as a type. You'd have to call Validate by passing an instance of UsersJSON, which you could then unmarshal the JSON into directly. It seems like what you're likely looking for is instead something like this:

    func MyFunc(w http.ResponseWriter, r *http.Request) {
        var unmarshaled UsersJSON
        errors, _ := schema.Validate(&unmarshaled)
    }
    
    func Validate(schemaHelper interface{}) (error) {
        file, err := os.Open("config/schema/schema.json")
        if err != nil {
            return nil, err
        }
    
        defer file.Close()
    
        byteValue, _ := ioutil.ReadAll(file)
    
        return json.Unmarshal(byteValue, schemaHelper)
    }
    

    This would unmarshal the JSON into the variable schemaHelper (whatever type it might be), for the caller to then use as it sees fit. Note that this is a rough best guess, because in your question the call to Validate passes 3 parameters but the function definition given only accepts 1 parameter.

    However, I don't think this does "validation" in the way that you think it does based on the question. It only validates that the JSON is syntactically valid, not that it has any relation to the struct you pass in - it could have fields that aren't defined in the struct, it could be missing fields that are defined, and it will not return any errors.

    Lastly, the type UsersJSON has no exported fields (all the fields begin with a lower-case letter, making them unexported/private), so nothing will be unmarshaled into it no matter what. encoding/json can only unmarshal into exported fields.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 经gamit解算的cors站数据再经globk网平差得到的坐标做形变分析
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式