-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
55 lines (45 loc) · 1.23 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package format
import (
"net/http"
"strings"
"github.com/gorilla/mux"
"github.com/u3mur4/crypto-price/exchange"
)
// NewServer displays the market as json format
func NewServer() Formatter {
return &serverFormatter{
markets: make(map[string]exchange.Market),
jsonFormatter: NewJSON().(*jsonFormat),
}
}
type serverFormatter struct {
markets map[string]exchange.Market
jsonFormatter *jsonFormat
}
func (j *serverFormatter) Open() {
j.jsonFormatter.Open()
rtr := mux.NewRouter()
rtr.HandleFunc("/{key:.*}", j.handler).Methods("GET")
http.Handle("/", rtr)
go http.ListenAndServe(":23232", nil)
}
func (j *serverFormatter) handler(w http.ResponseWriter, r *http.Request) {
key := strings.ToLower(r.URL.Path[1:])
// fmt.Println("New request for " + key)
if chart, ok := j.markets[key]; ok {
w.Header().Set("Content-Type", "application/json")
j.jsonFormatter.Output = w
j.jsonFormatter.Show(chart)
// fmt.Printf("Response:\n%s", string(b))
} else {
w.WriteHeader(404)
}
}
func (j *serverFormatter) Show(market exchange.Market) {
key := market.Exchange + ":" + market.Base + "-" + market.Quote
key = strings.ToLower(key)
j.markets[key] = market
}
func (j *serverFormatter) Close() {
j.jsonFormatter.Close()
}