-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpd.go
97 lines (80 loc) · 1.81 KB
/
httpd.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
package tcpmux
import (
"fmt"
"log"
"net"
"net/http"
"github.com/MoZhonghua/mytools/util"
"github.com/gorilla/mux"
)
type Httpd struct {
m *Tcpmux
s *Store
logger *log.Logger
}
func NewHttpd(m *Tcpmux, s *Store, logger *log.Logger) *Httpd {
d := &Httpd{
m: m,
s: s,
logger: logger,
}
return d
}
func (d *Httpd) Serv(port int) error {
m := mux.NewRouter()
m.Methods("POST").Path("/add").HandlerFunc(d.handleAddTarget)
m.Methods("DELETE").Path("/delete").HandlerFunc(d.handleDeleteTarget)
m.Methods("GET").Path("/list").HandlerFunc(d.handleListTarget)
l, err := net.Listen("tcp4", fmt.Sprintf(":%d", port))
if err != nil {
return err
}
return http.Serve(l, m)
}
func (d *Httpd) handleAddTarget(w http.ResponseWriter, r *http.Request) {
ti := &TargetInfo{}
err := util.ParseJsonRequest(r, ti)
if err != nil {
util.WriteErrorResponse(w, 400, err)
return
}
_, err = net.ResolveTCPAddr("tcp4", ti.Target)
if err != nil {
util.WriteErrorResponse(w, 400, err)
return
}
err = d.s.AddTarget(ti)
if err != nil {
util.WriteErrorResponse(w, 500, err)
return
}
err = d.m.AddTarget(ti.Id, ti.Target)
if err != nil {
d.s.DeleteTarget(ti.Id)
util.WriteErrorResponse(w, 500, err)
return
}
util.WriteSuccessResponse(w)
}
func (d *Httpd) handleDeleteTarget(w http.ResponseWriter, r *http.Request) {
id, err := util.QueryParam(r, "id")
if err != nil {
util.WriteErrorResponse(w, 400, err)
return
}
err = d.s.DeleteTarget(id)
if err != nil {
util.WriteErrorResponse(w, 500, err)
return
}
err = d.m.DeleteTarget(id)
if err != nil {
util.WriteErrorResponse(w, 500, err)
return
}
util.WriteSuccessResponse(w)
}
func (d *Httpd) handleListTarget(w http.ResponseWriter, r *http.Request) {
list := d.m.ListTarget()
util.WriteSuccessResponseWithData(w, list)
}