package http import ( "net/http" "net/url" "strconv" "strings" "github.com/kcotugno/tacitus" ) type TradeHandler struct { TradeService tacitus.TradeService } type tradesResponse struct { Trades []tacitus.Trade `json:"trades,omitempty"` Error string `json:"error,omitempty"` } func (t *TradeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { paths := strings.Split(r.URL.Path, "/") if len(paths) < 3 || !tacitus.ValidProduct(paths[3]) { errorResp(w, tacitus.Error("Invalid product")) return } params := r.URL.Query() params.Set("product", paths[3]) switch r.Method { case "GET": t.getTrades(w, params) default: errorResp(w, tacitus.Error("Invalid request")) } } func (t *TradeHandler) getTrades(w http.ResponseWriter, params url.Values) { var trades []tacitus.Trade var err error limit := parseLimit(params.Get("limit")) prod := params.Get("product") after, _ := strconv.ParseInt(params.Get("after"), 10, 0) before, _ := strconv.ParseInt(params.Get("before"), 10, 0) if params.Get("after") != "" { trades, err = t.TradeService.TradesAfter(prod, int(after), limit) } else if params.Get("before") != "" { trades, err = t.TradeService.TradesBefore(prod, int(before), limit) } else { trades, err = t.TradeService.LastTrades(prod, limit) } if err == nil { encodeJson(w, &tradesResponse{Trades: trades}) } else { errorResp(w, tacitus.Error("Invalid request")) } } func parseLimit(limit string) int { l, err := strconv.ParseInt(limit, 10, 0) if err != nil { l = 1000 } if l > 1000 { l = 1000 } return int(l) }