From 4811e24dd67b28b91d687d44291c92dc67dc8fe7 Mon Sep 17 00:00:00 2001 From: Garritt McCune Date: Tue, 7 Sep 2021 21:56:48 -0500 Subject: [PATCH] Fixed a bug where the postgres queries failed with a relation error. /data now dumps all the categories in the database. --- cmd/inv/main.go | 45 +++++++++++++++++++++++++++++++++++++++------ 1 file changed, 39 insertions(+), 6 deletions(-) diff --git a/cmd/inv/main.go b/cmd/inv/main.go index 5f01ed5..e672074 100644 --- a/cmd/inv/main.go +++ b/cmd/inv/main.go @@ -2,7 +2,7 @@ package main import ( "database/sql" - _ "encoding/json" + "encoding/json" "fmt" "net/http" "time" @@ -10,6 +10,7 @@ import ( _ "github.com/lib/pq" ) +//Go Best practices: https://github.com/golovers/effective-go type Item struct { Id int32 `json:"id"` Name int32 `json:"name"` @@ -46,12 +47,30 @@ func main() { } func get(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusBadGateway) - w.Write([]byte("Hell world!")) + c := sql_test() + + // if c.Id == 0 { + // w.WriteHeader(http.StatusBadGateway) + // w.Write([]byte("Failed")) + // return + // } + + jsonBytes, err := json.Marshal(c) + + if err != nil { + w.WriteHeader(http.StatusMethodNotAllowed) + w.Write([]byte("Failed 3")) + return + } + + w.WriteHeader(http.StatusOK) + w.Write(jsonBytes) } -func sql_test() { - psqlInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", "localhost", 5432, "postgres", "", "inventory") +func sql_test() []Category { + //Note: The postgres driver seems to get confused when no password is supplied, so omit it in the connection sting. + //https://rajyavardhan.medium.com/when-you-get-relation-does-not-exist-in-postgres-7ffb0c3c674b + psqlInfo := fmt.Sprintf("host=%s port=%d user=%s dbname=%s sslmode=disable", "localhost", 5432, "postgres", "inventory") db, err := sql.Open("postgres", psqlInfo) if err != nil { @@ -60,11 +79,25 @@ func sql_test() { defer db.Close() - rows, err := db.Query("") + rows, err := db.Query("SELECT * FROM category;") if err != nil { panic(err) } defer rows.Close() + + var categories []Category + + for rows.Next() { + var category Category + + if err = rows.Scan(&category.Id, &category.Name); err != nil { + println(err.Error()) + } + + categories = append(categories, category) + } + + return categories }