如何解决无法引用未导出的字段或方法模型。golang中的Model.getDevices

时间:2019-02-05 10:11:17

标签: go sqlite

entities.go

包装实体

类型设备结构{

Id        int    
Name      string 

}

models.go

package models

导入(

"log"
"net/http"
entities "../entities"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"

各种设备[] entities.Device

类型模型结构{}

func HttpInfo(r * http.Request){

fmt.Printf("%s\t %s\t %s%s\r\n", r.Method, r.Proto, r.Host, r.URL)

}

func(c模型)getDevices(db * gorm.DB)http.HandlerFunc {

return func(w http.ResponseWriter, r *http.Request) {

    setJsonHeader(w)

    HttpInfo(r)
    var devices entities.Device
    if err := db.Find(&devices).Error; err != nil {
        fmt.Println(err)
    } else {
        json.NewEncoder(w).Encode(devices)

    }
}

}

main.go

package main

导入(

"log"
"net/http"

entities "./src/entities"
models "./src/models"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"

各种设备[] entities.Device

var db * gorm.DB

var err error

func main(){

// Handle Subsequent requests

fmt.Println("Api running on port 4000...")

r := mux.NewRouter().StrictSlash(true)


r.HandleFunc("/devices", model.getDevices(db)).Methods("GET")

r.HandleFunc("/devices/{id}", model.getDevice).Methods("GET")


log.Fatal(http.ListenAndServe(":4000", handlers.CORS(headers, methods, origins)(r)))

}

1 个答案:

答案 0 :(得分:2)

您只是无法访问未导出的符号。未导出的全部原因是您无法访问它。无法解决,因此您必须导出该方法。对于此类基本问题,我可以推荐“围棋之旅”。

相关问题