I'm learning to use PostgreSQL and GORM. I'm creating a struct, connecting to database, and trying to write in to database.
Source code:
db, err := gorm.Open("postgres","user=superuser password=ojcafizp123 dbname=gorm sslmode=disable")
if err != nil {
panic(err.Error())
}
defer db.Close()
database := db.DB()
err = database.Ping()
if err != nil {
panic(err.Error())
}
fmt.Println("Connection to PostgreSQL was successful!")
port := ":3000"
r := chi.NewRouter()
r.Get("/api/test",Test)
http.ListenAndServe(port, r)
}
func CreateRate (w http.ResponseWriter, r *http.Request) {
db, err := gorm.Open("postgres","user=superuser password=ojcafizp123 dbname=gorm sslmode=disable")
cure := Crypto{"BTC","USD",10000,100}
if db.NewRecord(cure) {
err = db.Create(&cure).Error
if err != nil{
panic(err.Error())
}
}
}
Struct:
type Crypto struct {
Cur1 string `json:"cur1"`
Cur2 string `json:"cur2"`
Rate float64 `json:"rate"`
Timestamp int64 `json:"timestamp"`
}
Trying to find my record in the database:
func Test (w http.ResponseWriter, r *http.Request) {
db, err := gorm.Open("postgres","user=superuser password=ojcafizp123 dbname=gorm sslmode=disable")
var testcur Crypto
db.First(&testcur)
fmt.Println(testcur)
if err != nil {
fmt.Println("No testcur detected")
}
}
But got this:
Connection to PostgreSQL was successful! { 0 0}
(/home/superuser/go/src/CryptoProject/main.go:97) [2019-07-27 05:09:10] pq: relation "cryptos" does not exist
The connection is working, but the base is still empty.