-
Notifications
You must be signed in to change notification settings - Fork 153
/
handler.go
67 lines (61 loc) · 1.79 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
package handler
import (
"fmt"
"log"
"net/http"
"reflect"
"strings"
"time"
"github.com/hprose/hprose-golang/rpc"
"github.com/phonegapX/QuantBot/config"
"github.com/phonegapX/QuantBot/constant"
)
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
}{}
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
})
service.AddAllMethods(handler)
http.Handle("/api", service)
http.Handle("/", http.FileServer(http.Dir("web/dist")))
fmt.Printf("%v Version %v\n", constant.Banner, constant.Version)
log.Printf("Running at http://localhost:%v\n", port)
http.ListenAndServe(":"+port, nil)
}