diff --git a/db.go b/db.go index 0c47090..877583f 100644 --- a/db.go +++ b/db.go @@ -19,7 +19,6 @@ func initDB() *gorp.DbMap { dbmap.AddTableWithName(User{}, "users").SetKeys(true, "UserId") dbmap.AddTableWithName(Session{}, "sessions").SetKeys(true, "SessionId") dbmap.AddTableWithName(Account{}, "accounts").SetKeys(true, "AccountId") - dbmap.AddTableWithName(Security{}, "security").SetKeys(true, "SecurityId") dbmap.AddTableWithName(Transaction{}, "transactions").SetKeys(true, "TransactionId") dbmap.AddTableWithName(Split{}, "splits").SetKeys(true, "SplitId") diff --git a/main.go b/main.go index 6a8389a..28211a1 100644 --- a/main.go +++ b/main.go @@ -62,6 +62,7 @@ func main() { servemux.HandleFunc("/static/", staticHandler) servemux.HandleFunc("/session/", SessionHandler) servemux.HandleFunc("/user/", UserHandler) + servemux.HandleFunc("/security/", SecurityHandler) listener, err := net.Listen("tcp", ":"+strconv.Itoa(port)) if err != nil { diff --git a/securities.go b/securities.go index 9790b38..6967079 100644 --- a/securities.go +++ b/securities.go @@ -1,5 +1,11 @@ package main +import ( + "encoding/json" + "log" + "net/http" +) + type SecurityType int64 const ( @@ -17,3 +23,81 @@ type Security struct { Precision int64 Type SecurityType } + +type SecurityList struct { + Securities *[]*Security `json:"securities"` +} + +var security_map = map[int64]*Security{ + 1: &Security{ + SecurityId: 1, + Name: "USD", + Precision: 2, + Type: Banknote}, + 2: &Security{ + SecurityId: 2, + Name: "SPY", + Precision: 5, + Type: Stock}, +} + +var security_list []*Security + +func init() { + for _, value := range security_map { + security_list = append(security_list, value) + } +} + +func GetSecurity(securityid int64) *Security { + s := security_map[securityid] + if s != nil { + return s + } + return nil +} + +func GetSecurities() []*Security { + return security_list +} + +func (s *Security) Write(w http.ResponseWriter) error { + enc := json.NewEncoder(w) + return enc.Encode(s) +} + +func (sl *SecurityList) Write(w http.ResponseWriter) error { + enc := json.NewEncoder(w) + return enc.Encode(sl) +} + +func SecurityHandler(w http.ResponseWriter, r *http.Request) { + if r.Method == "GET" { + securityid, err := GetURLID(r.URL.Path) + if err == nil { + security := GetSecurity(securityid) + if security == nil { + WriteError(w, 3 /*Invalid Request*/) + return + } + err := security.Write(w) + if err != nil { + WriteError(w, 999 /*Internal Error*/) + log.Print(err) + return + } + } else { + var sl SecurityList + securities := GetSecurities() + sl.Securities = &securities + err := (&sl).Write(w) + if err != nil { + WriteError(w, 999 /*Internal Error*/) + log.Print(err) + return + } + } + } else { + WriteError(w, 3 /*Invalid Request*/) + } +}