【问题标题】:"..." undefined ("..." type has no field or method "...")"..." undefined ("..." 类型没有字段或方法 "...")
【发布时间】:2018-12-27 15:13:22
【问题描述】:

我正在为我的 go api 设置 crud 操作。创建所有函数后,我收到错误“app.createApplication undefined (type Application has no field or method createApplication)”,尽管我已经创建了它。

  • 确保变量与现有包的名称不同,因为堆栈溢出的其他问题已说明。

api.go

package controllers

import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"time"

"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
_ "github.com/lib/pq"
_ "gitlab.torq.trans.apps.ge.com/503081542/k-auth-api/models"
)

var err error

type API struct {
Database *gorm.DB
Router   *mux.Router
}

func (api *API) Initialize(opts string) 
{
// Initialize DB

var driver = "postgres"
var host = os.Getenv("DB_HOST")
var dbname = os.Getenv("DB_NAME")
var user = os.Getenv("DB_USER")
var password = os.Getenv("DB_PASSWORD")
var port = os.Getenv("DB_PORT")
var conn = fmt.Sprintf("host=%v dbname=%v user=%v password=%v port=%v sslmode=disable", host, dbname, user, password, port)
api.Database, err = gorm.Open(driver, conn)

if err != nil {
    log.Print("failed to connect to the database")
    log.Fatal(err)
}

fmt.Println("Connection estabished")

// Application Model

type Application struct {
    ID        string `json:"id" gorm:"primary_key"`
    AccessId  int64
    CreatedAt time.Time `json:"-"`
    UpdatedAt time.Time `json:"-"`
    Name      string    `json:"name"`
    Ci        string    `json:"ci"`
}

if !api.Database.HasTable(&Application{}) {
    api.Database.CreateTable(&Application{})
}

// Initialize Router
api.Router = mux.NewRouter()
api.Router.HandleFunc("/api/v1/applications", api.handleApplications)
api.Router.HandleFunc("/api/v1/application/{id}", api.handleApplication)
api.Router.HandleFunc("/api/v1/applications", api.getApplications).Methods("GET")
http.Handle("/", api.Router)
}
func (api *API) getApplications(w http.ResponseWriter, r *http.Request) {
type Application struct {
    ID        string `json:"id" gorm:"primary_key"`
    AccessId  int64
    CreatedAt time.Time `json:"-"`
    UpdatedAt time.Time `json:"-"`
    Name      string    `json:"name"`
    Ci        string    `json:"ci"`
}
count, _ := strconv.Atoi(r.FormValue("count"))
start, _ := strconv.Atoi(r.FormValue("start"))

if count > 10 || count < 1 {
    count = 10
}
if start < 0 {
    start = 0
}

applications, err := getApplications(api.Database, start, count)
if err != nil {
    respondWithError(w, http.StatusInternalServerError, err.Error())
    return
}

respondWithJSON(w, http.StatusOK, applications)
}

func respondWithError(w http.ResponseWriter, code int, message string) {
respondWithJSON(w, code, map[string]string{"error": message})
}
func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
response, _ := json.Marshal(payload)

w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}

main.go

package main

import (
    "log"
    "net/http"

    "github.com/gorilla/handlers"
    "gitlab.torq.trans.apps.ge.com/503081542/k-auth-api/controllers"
)

var err error

func main() {
    api := controllers.API{}
    api.Initialize("DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, DB_PORT sslmode=disable connect_timeout=5")
    // api.Initialize("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable connect_timeout=5")

    // Bind to a port and pass our router in
    log.Fatal(http.ListenAndServe(":8000", handlers.CORS()(api.Router)))

    if err != nil {
        panic(err.Error())
    }
}

【问题讨论】:

  • 数百行未格式化的代码不会帮助社区帮助您解决此问题。请将其简化为 Minimal, Complete, Verifiable Example,以说明只是您遇到的问题,在其上运行 gofmt,然后更新您的问题。
  • 错误信息很清楚:类型Application没有createApplication方法。 API 类型确实有一个 createApplication 方法。也许你打算这么称呼它。
  • 好的,我已经将它压缩为“getApplications”函数。

标签: go crud


【解决方案1】:
if err := app.createApplication(api.Database); err != nil {

您的 var app 具有 Application 类型,但方法 createApplicationAPI 类型相关联。我在代码中找不到 Application 的 createApplication 方法。

【讨论】:

  • 这是控制台中的错误。获取请求的方法如何? 1. app.createApplication undefined(类型Application没有字段或方法createApplication) 2. app.getApplication undefined(类型Application没有字段或方法getApplication) 3. app.updateApplication undefined(类型“gitlab.torq.trans.apps.ge .com/torq/torq-auth-api/models".Application 没有字段或方法 updateApplication) 4. app.deleteApplication undefined (type "gitlab.torq.trans.apps.ge.com/torq/torq-auth-api /models".Application 没有字段或方法 deleteApplication)
  • “App”指向 Application 结构,“api”指向 *API 结构。不完全确定缺少什么。我试过做这样的事情,但仍然得到错误。 func (app *Application) createApplication(db *gorm.DB) string { return (“Works”) }
  • 我将此答案作为评论发布,因为代码格式不正确。
猜你喜欢
  • 2017-08-03
  • 2017-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-10
  • 2014-08-26
  • 1970-01-01
相关资源
最近更新 更多