我没有错误,我也不知道为什么可以从模型包访问模型。 我也使用模块,这是我的go.mod文件:
module myapp
go 1.12
require (
github.com/badoux/checkmail v0.0.0-20181210160741-9661bd69e9ad
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/gorilla/mux v1.7.3
github.com/jinzhu/gorm v1.9.11
github.com/joho/godotenv v1.3.0
github.com/rs/cors v1.7.0
golang.org/x/crypto v0.0.0-20191108234033-bd318be0434a
)
user.go
和car.go
可以很好地导入,但是我添加的其余新模型不能很好地导入。
这是我的应用程序之树:
├── api
│ ├── auth
│ │ └── token.go
│ ├── controllers
│ │ ├── base.go
│ │ ├── car_location_controller.go
│ │ ├── cars_controller.go
│ │ ├── login_controller.go
│ │ ├── routers.go
│ │ └── users_controller.go
│ ├── middlewares
│ │ └── middlewares.go
│ ├── models
│ │ ├── Car.go
│ │ ├── CarLocation.go
│ │ ├── Rental.go
│ │ └── User.go
│ ├── responses
│ │ └── json.go
│ ├── server.go
│ └── utils
│ └── formaterror
│ └── formaterror.go
├── go.mod
├── go.sum
├── info.txt
└── main.go
我尝试将CarLocation.go
拨入car_location_controller.go
,但得到
包模型未声明CarLocation
这是我的CarLocation.go:
package models
import (
"errors"
"html"
"strings"
"time"
)
type CarLocation struct {
ID uint32 `gorm:"primary_key;auto_increment" json:"id"`
CarID uint32 `gorm:"int" json:"user_id"`
Car Car `json:"car"`
Street string `json:"street"`
City string `json:"city"`
State string `json:"state"`
Country string `json:"country"`
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
UpdatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"updated_at"`
}
func (l *CarLocation) Prepare() {
l.ID = 0
l.Street = html.EscapeString(strings.TrimSpace(l.Street))
l.City = html.EscapeString(strings.TrimSpace(l.City))
l.State = html.EscapeString(strings.TrimSpace(l.State))
l.CreatedAt = time.Now()
l.UpdatedAt = time.Now()
}
func (cl *CarLocation) Validate() error {
if cl.Street == "" {
return errors.New("Required Street")
}
if cl.City == "" {
return errors.New("Required City")
}
if cl.State == "" {
return errors.New("Required State")
}
return nil
}
这是我想在car_location_controller.go
中使用CarLocation的地方:
package controllers
import (
"encoding/json"
"io/ioutil"
"net/http"
"myapp/api/responses"
"myapp/api/models"
)
func (server *Server) CreateCarLocation(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
responses.ERROR(w, http.StatusUnprocessableEntity, err)
return
}
car := models.CarLocation{}
err = json.Unmarshal(body, &car)
if err != nil {
responses.ERROR(w, http.StatusUnprocessableEntity, err)
return
}
car.Prepare()
}