简体   繁体   English

Go 未知字段......在类型的结构文字中

[英]Go unknown field … in struct literal of type

I am trying to define routes based on a custom routes-struct (containing a Prefix and an array of Subroutes).我正在尝试基于自定义路由结构(包含前缀和子路由数组)定义路由。

I found the code in a tutorial and it worked as expected.我在教程中找到了代码,它按预期工作。 My goal is to also include a new attribute "IsSecure (bool)" in the struct so that I can later check if the Router should use a Middleware for the specific route prefix or not...我的目标是在结构中还包含一个新属性“IsSecure (bool)”,以便我以后可以检查路由器是否应该为特定的路由前缀使用中间件......

This is the file for struct:这是结构的文件:

var AppRoutes []RoutePrefix // used to append routes later in the main.go

type RoutePrefix struct {
    IsSecure bool // -> causes the problem
    Prefix string
    SubRoutes []Route
}

type Route struct {
    Name string
    Method string
    Pattern string
    HandlerFunc http.HandlerFunc
}

The problem now is that when I try to define a new RoutePrefix, Go returns the following error :现在的问题是,当我尝试定义新的 RoutePrefix 时, Go 返回以下错误

unknown field 'IsSecure' in struct literal of type router.RoutePrefix

If I remove the field "IsSecure" from the struct, everything works fine.如果我从结构中删除字段“IsSecure”,一切正常。

This is how I define the Routes:这就是我定义路线的方式:

var PostRoutes = router.RoutePrefix {
IsSecure:  true,
SubRoutes: []router.Route{
        {
            Name:        "CreatePost",
            Method:      "POST",
            Pattern:     "",
            HandlerFunc: CreatePostHandler,
        },
        {
            Name:        "DeletePost",
            Method:      "DELETE",
            Pattern:     "/{postId}",
            HandlerFunc: DeletePostHandler,
        },
    },
}

What could cause the problem?什么可能导致问题? I already tried to nest "RoutePrefix" in another struct that contains "IsSecure" which didn't work either.我已经尝试将“RoutePrefix”嵌套在另一个包含“IsSecure”的结构中,这也不起作用。

The problem was that I was unintentionally trying to override an already existing package containing this struct.问题是我无意中试图覆盖一个已经存在的包含这个结构的 package。

Changing the package solved the problem.更改 package 解决了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM