Fixed a bug where the postgres queries failed with a relation error. /data now dumps all the categories in the database.

This commit is contained in:
2021-09-07 21:56:48 -05:00
parent 6e4f7044e8
commit 4811e24dd6
+39 -6
View File
@@ -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
}