jjzjj

go - "..."未定义("..."类型没有字段或方法 "...")

coder 2024-07-14 原文

我正在为我的 go api 设置 crud 操作。创建所有函数后,我收到错误“app.createApplication undefined(类型 Application 没有字段或方法 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)
}

主.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())
    }
}

最佳答案

if err := app.createApplication(api.Database); err != nil {

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

关于go - "..."未定义("..."类型没有字段或方法 "..."),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53947175/

有关go - "..."未定义("..."类型没有字段或方法 "...")的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  5. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  6. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  7. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

  8. ruby - 难道Lua没有和Ruby的method_missing相媲美的东西吗? - 2

    我好像记得Lua有类似Ruby的method_missing的东西。还是我记错了? 最佳答案 表的metatable的__index和__newindex可以用于与Ruby的method_missing相同的效果。 关于ruby-难道Lua没有和Ruby的method_missing相媲美的东西吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/7732154/

  9. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  10. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

随机推荐