-
Notifications
You must be signed in to change notification settings - Fork 63
/
apiserver.go
113 lines (94 loc) · 2.52 KB
/
apiserver.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main
import (
"encoding/json"
"fmt"
"net/http"
"time"
log "github.com/golang/glog"
)
type request struct {
Act, Mobile, Code, Service, Uid string `json:",omitempty"`
result chan Result
}
func (r *request) String() string {
return fmt.Sprintf("%s\t%s\t%s\t%s\t%s", r.Act, r.Mobile, r.Code, r.Service, r.Uid)
}
type apiserver struct {
req []chan *request
}
func (api *apiserver) sms(i int) {
var (
infos interface{}
err error
result Result
)
sms := NewSms()
for req := range api.req[i] {
sms.NowTime = time.Now()
sms.SetServiceConfig(req.Service)
infos = nil
switch req.Act {
case "send":
err = sms.Send(req.Mobile)
case "checkcode":
err = sms.CheckCode(req.Mobile, req.Code)
case "setuid":
err = sms.SetUid(req.Mobile, req.Uid)
case "deluid":
err = sms.DelUid(req.Mobile, req.Uid)
case "info":
infos, err = sms.Info(req.Mobile)
default:
err = fmt.Errorf("%s\t%s", "API not found:", req.Act)
}
switch sms.Config.Outformat {
case "mobcent":
result = &Result_mobcent{}
default:
result = &Result_default{}
}
result.Format(err, infos)
req.result <- result
}
return
}
func (api *apiserver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log.Info(r.RemoteAddr, r.URL)
defer func() {
if e := recover(); e != nil {
err := fmt.Errorf("Server error :%s", e)
w.WriteHeader(500)
w.Write([]byte(err.Error()))
}
}()
resultchan := make(chan Result)
req := &request{r.URL.Path[1:], r.FormValue("mobile"), r.FormValue("code"), r.FormValue("service"), r.FormValue("uid"), resultchan}
hash := hashFunc([]byte(req.String())) & uint64(*smsworks-1)
for {
select {
case api.req[hash] <- req:
case result := <-resultchan:
w.Header().Set("Content-Type", ContentType)
w.Header().Set("TimeZone", time.Local.String())
str, _ := json.Marshal(result)
w.Write(str)
return
//未在预定时间内完成请求或者接收答复则报超时错误
//如果设置的smsworks过少时,当大量的并发请求因处理量受限无法及时处理。会使得请求或接受时间延长导致超时;
//另外网络不稳定或短信供应商通道出现了问题也会引起超时。
case <-time.After(config.TimeOut * time.Second):
panic("Server timeout error!")
}
}
}
func Apiserver() {
var api = new(apiserver)
api.req = make([]chan *request, *smsworks)
for i := 0; i < *smsworks; i++ {
go func(i int) {
api.req[i] = make(chan *request)
api.sms(i)
}(i)
}
log.Fatal(http.ListenAndServe(config.Bind, api))
}