added json encoding

This commit is contained in:
Nickiel12 2023-12-30 10:35:51 -08:00
parent 207e632157
commit 407d7ea9a5

View file

@ -2,23 +2,29 @@ package main
import ( import (
"database/sql" "database/sql"
"encoding/json"
"net/http"
"errors"
"fmt" "fmt"
"log" "log"
"os"
"time" "time"
"net/http"
"github.com/shopspring/decimal" "github.com/shopspring/decimal"
_ "github.com/lib/pq" _ "github.com/lib/pq"
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
) )
// "json:"json_code_name,omitempty"" (omit empty)
// if you use `json:"-"` it doesn't encode it
type Transaction struct { type Transaction struct {
Id int `db:"trns_id"` Id int `db:"trns_id" json:"Id"`
Amount decimal.Decimal `db:"trns_amount"` Amount decimal.Decimal `db:"trns_amount" json:"Amount"`
Description sql.NullString `db:"trns_description"` Description sql.NullString `db:"trns_description" json:"Description"`
Account int `db:"trns_account"` Account int `db:"trns_account" json:"Account"`
Bucket sql.NullInt64 `db:"trns_bucket"` Bucket sql.NullInt64 `db:"trns_bucket" json:"Bucket"`
Date time.Time `db:"trns_date"` Date time.Time `db:"trns_date" json:"TransactionDate"`
} }
func hello(w http.ResponseWriter, req *http.Request) { func hello(w http.ResponseWriter, req *http.Request) {
@ -61,7 +67,12 @@ func main() {
for _, trns := range transactions { for _, trns := range transactions {
if trns.Description.Valid { if trns.Description.Valid {
log.Print(fmt.Sprintf("%v : %#v", trns.Amount, trns.Id)) //bytes, err := json.Marshal(trns)
bytes, err := json.MarshalIndent(trns, "", "\t")
if err != nil {
log.Fatal(err)
}
log.Println(string(bytes))
} else { } else {
log.Print("amount invalid") log.Print("amount invalid")
} }
@ -69,10 +80,42 @@ func main() {
log.Print("select all run is done") log.Print("select all run is done")
/*
jsonExample := `{
"Id": 3,
"Amount": "100",
"Description": {
"String": "Transaction 3",
"Valid": true
},
"Account": 1,
"Bucket": {
"Int64": 1,
"Valid": true
},
"TransactionDate": "2023-11-11T00:00:00Z"
}`
var trns Transaction = Transaction{}
err = json.Unmarshal([]byte(jsonExample), &trns)
if err != nil {
log.Println(err)
} else {
log.Println(trns.Amount)
}
*/
http.HandleFunc("/hello", hello) http.HandleFunc("/hello", hello)
http.HandleFunc("/headers", headers) //http.HandleFunc("/headers", headers)
http.ListenAndServe(":8090", nil) http.ListenAndServe(":8090", nil)
if errors.Is(err, http.ErrServerClosed) {
fmt.Printf("server closed\n")
} else if err != nil {
fmt.Printf("error starting server: %s\n", err)
os.Exit(1)
}
//fmt.Println("Hello World") //fmt.Println("Hello World")
} }