This repository has been archived on 2022-11-30. You can view files and clone it, but cannot push or open issues or pull requests.
tacitus/http/trade_handler.go

77 lines
1.6 KiB
Go
Raw Normal View History

2017-09-09 10:14:50 -07:00
package http
import (
"net/http"
"net/url"
"strconv"
"strings"
2017-09-23 11:47:35 -07:00
2017-09-10 13:09:27 -07:00
"github.com/kcotugno/tacitus"
2017-09-09 10:14:50 -07:00
)
type TradeHandler struct {
TradeService tacitus.TradeService
2017-09-25 16:47:09 -07:00
logger tacitus.Logger
2017-09-09 10:14:50 -07:00
}
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, "/")
2017-09-10 13:04:02 -07:00
if len(paths) < 3 || !tacitus.ValidProduct(paths[3]) {
2017-09-09 10:14:50 -07:00
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)
}