-
Notifications
You must be signed in to change notification settings - Fork 2
/
handler.go
74 lines (68 loc) · 2.03 KB
/
handler.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package handler
import (
"fmt"
"log"
"net/http"
"reflect"
"strings"
"time"
"github.com/Impress-semirding/quant/config"
"github.com/Impress-semirding/quant/constant"
"github.com/hprose/hprose-golang/rpc"
)
type response struct {
Success bool
Message string
Data interface{}
}
type event struct{}
func (e event) OnSendHeader(ctx *rpc.HTTPContext) {
ctx.Response.Header().Set("Access-Control-Allow-Headers", "Authorization")
}
// Server ...
func Server() {
port := config.String("port")
service := rpc.NewHTTPService()
handler := struct {
User user
Exchange exchange
Algorithm algorithm
Trader runner
Log logger
ApiConfig apiConfig
}{}
service.Event = event{}
service.AddBeforeFilterHandler(func(request []byte, ctx rpc.Context, next rpc.NextFilterHandler) (response []byte, err error) {
ctx.SetInt64("start", time.Now().UnixNano())
httpContext := ctx.(*rpc.HTTPContext)
if httpContext != nil {
ctx.SetString("username", parseToken(httpContext.Request.Header.Get("Authorization")))
}
return next(request, ctx)
})
service.AddInvokeHandler(func(name string, args []reflect.Value, ctx rpc.Context, next rpc.NextInvokeHandler) (results []reflect.Value, err error) {
name = strings.Replace(name, "_", ".", 1)
results, err = next(name, args, ctx)
spend := (time.Now().UnixNano() - ctx.GetInt64("start")) / 1000000
spendInfo := ""
if spend > 1000 {
spendInfo = fmt.Sprintf("%vs", spend/1000)
} else {
spendInfo = fmt.Sprintf("%vms", spend)
}
log.Printf("%16s() spend %s", name, spendInfo)
return
})
fs := http.FileServer(http.Dir("web/dist"))
service.AddAllMethods(handler)
http.Handle("/api", service)
http.Handle("/", http.FileServer(http.Dir("web/dist")))
routes := []string{"login", "exchange", "quote", "algorithm"}
for _, v := range routes {
prefix := "/" + v + "/"
http.Handle(prefix, http.StripPrefix(prefix, fs))
}
fmt.Printf("%v Version %v\n", constant.Banner, constant.Version)
log.Printf("Running at http://localhost:%v\n", port)
http.ListenAndServe(":"+port, nil)
}