-
Notifications
You must be signed in to change notification settings - Fork 48
/
api.go
74 lines (73 loc) · 1.4 KB
/
api.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 msgserver
import(
"net/http"
"strings"
"encoding/json"
"fmt"
"io"
)
type Api struct{
Sender *Sender
}
func(this *Api) Listen(addr,path string){
h:=&httpHandler{
sender:this.Sender,
}
h.router=make(map [string]func(*Sender,http.ResponseWriter,*http.Request),0)
h.router[path]=msgSender
fmt.Printf("api listen address %s,path '%s'[post]\n",addr,path)
err:=http.ListenAndServe(addr,h)
if err!=nil{
panic(err)
}
}
// 消息发送 http api
func msgSender(sender *Sender,res http.ResponseWriter,req *http.Request){
if strings.ToUpper(req.Method)!="POST"{
return
}
var success=true
defer func(){
if(success){
res.Write([]byte("1"))
}else{
res.Write([]byte("0"))
}
}()
reader:= req.Body
buffer:=make([]byte,256)
le,err:=reader.Read(buffer)
if err!=nil && err!=io.EOF{
success=false
return
}
buffer=buffer[:le]
type msgContent struct{
To string
Content string
}
msg:=new(msgContent)
if json.Unmarshal(buffer,msg)!=nil{
success=false
return
}
if msg.To==""{
sender.SendNotice(msg.Content)
}else{
sender.SendMessage(msg.Content,msg.To)
}
}
// http handler
type httpHandler struct{
sender *Sender
router map [string]func(*Sender,http.ResponseWriter,*http.Request)
}
func(this *httpHandler) ServeHTTP(res http.ResponseWriter, req *http.Request){
path:=req.URL.Path
for k:=range this.router{
if k==path{
this.router[k](this.sender, res,req)
break
}
}
}