-
Notifications
You must be signed in to change notification settings - Fork 20
/
sub.go
100 lines (81 loc) · 1.88 KB
/
sub.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
package simplehttp
import (
"context"
"encoding/json"
"errors"
"net/http"
"sort"
"github.com/Asutorufa/yuhaiin/pkg/protos/node"
grpcnode "github.com/Asutorufa/yuhaiin/pkg/protos/node/grpc"
"google.golang.org/protobuf/types/known/emptypb"
)
type subHandler struct {
emptyHTTP
nm grpcnode.NodeManagerServer
}
func (s *subHandler) Post(w http.ResponseWriter, r *http.Request) error {
name := r.URL.Query().Get("name")
link := r.URL.Query().Get("link")
if name == "" || link == "" {
return errors.New("name or link is empty")
}
_, err := s.nm.SaveLinks(context.TODO(), &grpcnode.SaveLinkReq{
Links: []*node.NodeLink{
{
Name: name,
Url: link,
},
},
})
if err != nil {
return err
}
w.Write(nil)
return nil
}
func (s *subHandler) Get(w http.ResponseWriter, r *http.Request) error {
links, err := s.nm.GetLinks(context.TODO(), &emptypb.Empty{})
if err != nil {
return err
}
ls := make([]string, 0, len(links.Links))
for v := range links.Links {
ls = append(ls, v)
}
sort.Strings(ls)
return TPS.BodyExecute(w, map[string]any{"LS": ls, "Links": links.Links}, "sub.html")
}
func (s *subHandler) Delete(w http.ResponseWriter, r *http.Request) error {
data := r.URL.Query().Get("links")
if data == "" {
w.Write(nil)
return nil
}
var names []string
if err := json.Unmarshal([]byte(data), &names); err != nil {
return err
}
_, err := s.nm.DeleteLinks(context.TODO(), &grpcnode.LinkReq{Names: names})
if err != nil {
return err
}
w.Write(nil)
return nil
}
func (s *subHandler) Patch(w http.ResponseWriter, r *http.Request) error {
data := r.URL.Query().Get("links")
if data == "" {
w.Write(nil)
return nil
}
var names []string
if err := json.Unmarshal([]byte(data), &names); err != nil {
return err
}
_, err := s.nm.UpdateLinks(context.TODO(), &grpcnode.LinkReq{Names: names})
if err != nil {
return err
}
w.Write(nil)
return nil
}