我有一张用户表。我想编写一个 API 来使用 id 获取数据。我不断收到以下错误。请注意,数据库已经满了。我想创建一个获取 api,我在其中传递 id 并作为结果获取该行。我已经尝试了一些事情,但我一直收到此错误。 数据库架构-
deadpool=# \d user_data
Table "public.user_data"
Column | Type | Collation | Nullable | Default
--------------------+--------------------------+-----------+----------+---------------------------------------
id | integer | | not null | nextval('user_data_id_seq'::regclass)
created_at | timestamp with time zone | | |
updated_at | timestamp with time zone | | |
deleted_at | timestamp with time zone | | |
name | text | | |
age | text | | |
gender | text | | |
party_code | text | | |
criminal_cases | text | | |
number_of_cases | text | | |
serious_ipc_counts | text | | |
ipc_details | text | | |
education_level | text | | |
movable_assets | text | | |
immovable_assets | text | | |
total_assets | text | | |
total_liabilities | text | | |
pan_given | text | | |
election | text | | |
constituency | text | | |
Indexes:
"user_data_pkey" PRIMARY KEY, btree (id)
"idx_user_data_deleted_at" btree (deleted_at)
我的代码- 包主
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"log"
"net/http"
)
var db *gorm.DB
var err error
type UserData struct {
gorm.Model
Name string `json:"name"`
Age string `json:"age"`
Gender string `json:"gender"`
Party_Code string `json:"party_code"`
Criminal_Cases string `json:"criminal_cases"`
Number_of_Cases string `json:"number_of_cases"`
Serious_IPC_Counts string `json:"serious_ipc_counts"`
IPC_Details string `json:"ipc_details"`
Education_Level string `json:"education_level"`
Movable_Assets string `json:"movable_assets"`
Immovable_Assets string `json:"immovable_assets"`
Total_Assets string `json:"total_assets"`
Total_Liabilities string `json:"total_liabilities"`
PAN_Given string `json:"pan_given"`
Election string `json:"election"`
Constituency string `json:"constituency"`
}
func main() {
// NOTE: See we’re using = to assign the global var
// instead of := which would assign it only in this function
db, err := gorm.Open("postgres", "host=localhost port=5432 dbname=deadpool sslmode=disable")
if err != nil {
fmt.Println(err)
}
defer db.Close()
router := mux.NewRouter()
router.HandleFunc("/resources/{id}", GetResource).Methods("GET")
log.Fatal(http.ListenAndServe(":8080", router))
}
func GetResource(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
var userData UserData
db.First(&userData, params["id"])
json.NewEncoder(w).Encode(&userData)
}
我面临的错误-
> 2019/06/13 18:41:22 http: panic serving [::1]:56779: runtime error:
> invalid memory address or nil pointer dereference goroutine 47
> [running]: net/http.(*conn).serve.func1(0xc00020e460)
> /usr/local/Cellar/go/1.11.4/libexec/src/net/http/server.go:1746 +0xd0
> panic(0x13ba240, 0x1714f30)
> /usr/local/Cellar/go/1.11.4/libexec/src/runtime/panic.go:513 +0x1b9 github.com/jinzhu/gorm.(*DB).clone(0x0, 0x10)
> /Users/abhisekroy/go/src/github.com/jinzhu/gorm/main.go:768 +0x26 github.com/jinzhu/gorm.(*DB).NewScope(0x0, 0x1384740, 0xc000244500, 0x0)
> /Users/abhisekroy/go/src/github.com/jinzhu/gorm/main.go:179 +0x2f github.com/jinzhu/gorm.(*DB).First(0x0, 0x1384740, 0xc000244500, 0xc00018a830, 0x1, 0x1, 0x12cdeda)
> /Users/abhisekroy/go/src/github.com/jinzhu/gorm/main.go:299 +0x5a main.GetResource(0x1490560, 0xc000240380, 0xc000189600)
> /Users/abhisekroy/go/src/github.com/CreditSaisonIndia/deadpool/ExternalVerifications/externalVerifications.go:49
> +0x13d net/http.HandlerFunc.ServeHTTP(0x143ba08, 0x1490560, 0xc000240380, 0xc000189600)
> /usr/local/Cellar/go/1.11.4/libexec/src/net/http/server.go:1964 +0x44
> github.com/gorilla/mux.(*Router).ServeHTTP(0xc0000ec480, 0x1490560,
> 0xc000240380, 0xc00022b200)
> /Users/abhisekroy/go/src/github.com/gorilla/mux/mux.go:212 +0xd0 net/http.serverHandler.ServeHTTP(0xc000087520, 0x1490560, 0xc000240380, 0xc00022b200)
> /usr/local/Cellar/go/1.11.4/libexec/src/net/http/server.go:2741 +0xab
> net/http.(*conn).serve(0xc00020e460, 0x14908a0, 0xc000224880)
> /usr/local/Cellar/go/1.11.4/libexec/src/net/http/server.go:1847 +0x646
> created by net/http.(*Server).Serve
> /usr/local/Cellar/go/1.11.4/libexec/src/net/http/server.go:2851 +0x2f5
> 2019/06/13 18:41:22 http: panic serving [::1]:56780: runtime error:
> invalid memory address or nil pointer dereference goroutine 48
> [running]: net/http.(*conn).serve.func1(0xc00020e500)
> /usr/local/Cellar/go/1.11.4/libexec/src/net/http/server.go:1746 +0xd0
> panic(0x13ba240, 0x1714f30)
> /usr/local/Cellar/go/1.11.4/libexec/src/runtime/panic.go:513 +0x1b9 github.com/jinzhu/gorm.(*DB).clone(0x0, 0x10)
> /Users/abhisekroy/go/src/github.com/jinzhu/gorm/main.go:768 +0x26 github.com/jinzhu/gorm.(*DB).NewScope(0x0, 0x1384740, 0xc00026c780, 0x0)
> /Users/abhisekroy/go/src/github.com/jinzhu/gorm/main.go:179 +0x2f github.com/jinzhu/gorm.(*DB).First(0x0, 0x1384740, 0xc00026c780, 0xc000226250, 0x1, 0x1, 0x12cdeda)
> /Users/abhisekroy/go/src/github.com/jinzhu/gorm/main.go:299 +0x5a main.GetResource(0x1490560, 0xc000266540, 0xc00022b600)
> /Users/abhisekroy/go/src/github.com/CreditSaisonIndia/deadpool/ExternalVerifications/externalVerifications.go:49
> +0x13d net/http.HandlerFunc.ServeHTTP(0x143ba08, 0x1490560, 0xc000266540, 0xc00022b600)
> /usr/local/Cellar/go/1.11.4/libexec/src/net/http/server.go:1964 +0x44
> github.com/gorilla/mux.(*Router).ServeHTTP(0xc0000ec480, 0x1490560,
> 0xc000266540, 0xc00022b400)
> /Users/abhisekroy/go/src/github.com/gorilla/mux/mux.go:212 +0xd0 net/http.serverHandler.ServeHTTP(0xc000087520, 0x1490560, 0xc000266540, 0xc00022b400)
> /usr/local/Cellar/go/1.11.4/libexec/src/net/http/server.go:2741 +0xab
> net/http.(*conn).serve(0xc00020e500, 0x14908a0, 0xc000224980)
> /usr/local/Cellar/go/1.11.4/libexec/src/net/http/server.go:1847 +0x646
> created by net/http.(*Server).Serve
> /usr/local/Cellar/go/1.11.4/libexec/src/net/http/server.go:2851 +0x2f5
最佳答案
您没有设置包级 db var,因为您使用 :=。
并在出现错误时退出 main 函数,这样您就不会继续使用 nil db。
var db *gorm.DB
func main() {
var err error
db, err = gorm.Open()
if err != nil {
log.Fatalf("unable to connect to database: %s", err.Error())
}
}
关于go - 我有一张用户表。我想编写一个 API 来使用 id 获取数据。我不断收到以下错误。请注意,数据库已经满了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56581377/
大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test
我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c
有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file
我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe
在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee
我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie
有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳