从另一个包引用结构域

I have the following folder structure:

.
├── Makefile
├── README.md
├── myproject
│   ├── handlers
│   │   └── authorize_handler.go
│   ├── models
│   │   ├── id_token.go
│   ├── server.go

From authorize_handler.go I try to reference the IdToken.idType field from the id_token.go file.

authorize_handler.go

package handlers

import (
    "encoding/json"
    "log"
    "net/http"

    "myproject/models"
)

func AuthorizeHandler(rw http.ResponseWriter, req *http.Request) {
    idToken := new(models.IdToken)

    decoder := json.NewDecoder(req.Body)
    err := decoder.Decode(&idToken)
    if err != nil {
        panic(err)
    }

    log.Println(idToken.idType)
}

id_token.go

package models

type IdToken struct {
    id     string `json:"id" type:"string" required:"true" max_length:"50"`
    idType string `json:"idType" type:"idType" required:"false"`
}

When I start server.go using go run server.go I get the following error:

handlers/authorize_handler.go:29: idToken.idType undefined (cannot refer to unexported field or method idType)

Moving the IdToken to the authorize_handler.go does solve the problem. Changing idType to IdType does not.

Any ideas or pointers to share?

The only way it will work as you currently have it imported is if the myproject/models package is in your $GOPATH/src directory, since that is where it is looking for it when you tell it to import without a file path.

Alternatively, you could reference using a relative path such as ../models but that can get messy. Also, this sort of file structure tends to lead to cyclical dependencies, so be aware of making sure you avoid that if you go with this method.

Edit: As captncraig pointed out, the compiler seems to find the package ok, so this is more likely that your field within the struct is not exported because it starts with a lowercase character in the definition. Just changing it to a capital letter will make it publicly accessible from outside the package.

type IdToken struct {
    Id     string `json:"id" type:"string" required:"true" max_length:"50"`
    IdType string `json:"idType" type:"idType" required:"false"`
}