Files
inventory-middleware/cmd/inv/main.go
T

104 lines
2.2 KiB
Go

package main
import (
"database/sql"
"encoding/json"
"fmt"
"net/http"
"time"
_ "github.com/lib/pq"
)
//Go Best practices: https://github.com/golovers/effective-go
type Item struct {
Id int32 `json:"id"`
Name int32 `json:"name"`
ValueCents int32 `json:"valueCents"`
PurchaseCostCents int32 `json:"purchasedCostCents"`
Aquired time.Time `json:"aquired"`
Description string `json:"description"`
Notes string `json:"notes"`
SoldForCents int32 `json:"soldForCents"`
SoldTo string `json:"soldTo"`
Category Category `json:"category"`
Subcategory Subcategory `json:"subcategory"`
}
type Category struct {
Id int32 `json:"id"`
Name string `json:"name"`
}
type Subcategory struct {
Id int32 `json:"id"`
Name string `json:"name"`
CategoryId int32 `json:"categoryId"`
}
func main() {
http.HandleFunc("/data", get)
err := http.ListenAndServe(":8080", nil)
if err != nil {
panic(err)
}
}
func get(w http.ResponseWriter, r *http.Request) {
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() []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 {
panic(err)
}
defer db.Close()
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
}