69 lines
1.9 KiB
Go
69 lines
1.9 KiB
Go
package server
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"github.com/gorilla/mux"
|
|
)
|
|
|
|
type watchlistItem struct {
|
|
ID int `json:"id"`
|
|
Ticker string `json:"ticker"`
|
|
Name string `json:"name"`
|
|
Sector string `json:"sector"`
|
|
Exchange string `json:"exchange"`
|
|
Active int `json:"active"`
|
|
}
|
|
|
|
func (s *Server) handleGetWatchlist(w http.ResponseWriter, r *http.Request) {
|
|
rows, err := s.db.Query(`SELECT id, ticker, COALESCE(name,''), COALESCE(sector,''), COALESCE(exchange,''), active FROM watchlist WHERE active=1 ORDER BY ticker`)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
defer rows.Close()
|
|
|
|
items := []watchlistItem{}
|
|
for rows.Next() {
|
|
var it watchlistItem
|
|
if err := rows.Scan(&it.ID, &it.Ticker, &it.Name, &it.Sector, &it.Exchange, &it.Active); err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
items = append(items, it)
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(items)
|
|
}
|
|
|
|
func (s *Server) handleAddWatchlist(w http.ResponseWriter, r *http.Request) {
|
|
var body struct {
|
|
Ticker string `json:"ticker"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.Ticker == "" {
|
|
http.Error(w, "ticker required", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
_, err := s.db.Exec(`INSERT OR IGNORE INTO watchlist (ticker) VALUES (?)`, body.Ticker)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusCreated)
|
|
w.Write([]byte(`{"status":"added"}`))
|
|
}
|
|
|
|
func (s *Server) handleRemoveWatchlist(w http.ResponseWriter, r *http.Request) {
|
|
ticker := mux.Vars(r)["ticker"]
|
|
s.db.Exec(`DELETE FROM watchlist WHERE ticker = ?`, ticker)
|
|
s.db.Exec(`DELETE FROM signals WHERE ticker = ? AND source = 'watchlist'`, ticker)
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.Write([]byte(`{"status":"removed"}`))
|
|
}
|