-
Notifications
You must be signed in to change notification settings - Fork 0
/
resou.go
216 lines (203 loc) · 5.86 KB
/
resou.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package main
import (
"fmt"
"net/http"
// "html/template"
"encoding/json"
"github.com/didip/tollbooth"
"github.com/tidwall/gjson"
"github.com/urfave/cli"
"golang.org/x/sync/errgroup"
"io/ioutil"
"log"
"os"
"regexp"
"strconv"
)
type Value struct {
Index int `json:"index"`
WordQuery string `json:"wordQuery"`
Desc string `json:"desc"`
Img string `json:"img"`
RawUrl string `json:"rawUrl"`
HotScore int `json:"hotScore"`
HotTag int `json:"hotTag"`
HotTagImg string `json:"hotTagImg"`
}
type Data struct {
Text string `json:"text"`
Value []Value `json:"value"`
}
type Datavalue struct {
Data []Data `json:"data"`
Retcode int `json:"retcode"`
Status string `json:"status"`
Wording string `json:"wording"`
}
func grabReSouData(sum int) Datavalue {
//抓取热榜数据
resp, err := http.Get("https://top.baidu.com/board?tab=realtime")
if err != nil {
// handle error
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
panic(err)
}
//解析正则表达式,如果成功返回解释器
reg := regexp.MustCompile(`<\!--s-data:({.*})-->{1}`)
if reg == nil {
fmt.Println("regexp err")
panic(reg)
}
//根据规则提取关键信息
result := reg.FindAllStringSubmatch(string(body), -1)
text := gjson.Get(result[0][1], "data.cards.0.text").Str //热榜名
var d Data
for i := 0; ; i++ {
index := gjson.Get(result[0][1], "data.cards.0.content."+strconv.Itoa(i)+".index") //排名
if !index.Exists() || i >= sum {
break
} else {
wordQuery := gjson.Get(result[0][1], "data.cards.0.content."+strconv.Itoa(i)+".word").Str //描述
desc := gjson.Get(result[0][1], "data.cards.0.content."+strconv.Itoa(i)+".desc").Str //摘要,为空则无摘要
img := gjson.Get(result[0][1], "data.cards.0.content."+strconv.Itoa(i)+".img").Str //缩略图
rawUrl := gjson.Get(result[0][1], "data.cards.0.content."+strconv.Itoa(i)+".rawUrl").Str //详情链接
hotScore := gjson.Get(result[0][1], "data.cards.0.content."+strconv.Itoa(i)+".hotScore") //热度指数
hotTag := gjson.Get(result[0][1], "data.cards.0.content."+strconv.Itoa(i)+".hotTag") //标签,为0则无标签 /* 3 热 2 商 1 新 0 无 */
hotTagImg := gjson.Get(result[0][1], "data.cards.0.content."+strconv.Itoa(i)+".hotTagImg").Str //标签图标,如果标签为0则此项为空
d.Value = append(d.Value, Value{
Index: int(index.Int()),
WordQuery: wordQuery,
Desc: desc,
Img: img,
RawUrl: rawUrl,
HotScore: int(hotScore.Int()),
HotTag: int(hotTag.Int()),
HotTagImg: hotTagImg,
})
}
}
d.Text = text
dv := Datavalue{
Data: []Data{
d,
},
Retcode: 200,
Status: "success",
Wording: "ok",
}
return dv
}
func handleReSouGetIsPost(writer http.ResponseWriter, request *http.Request) {
// 处理application/json类型的POST请求,根据请求body创建一个json解析器实例
decoder := json.NewDecoder(request.Body)
// 用于存放参数key=value数据
var params map[string]string
// 解析参数 存入map
decoder.Decode(¶ms)
if params["sum"] != "" {
sum, err := strconv.Atoi(params["sum"])
if err != nil {
writer.WriteHeader(http.StatusInternalServerError)
writer.Write([]byte(`{"data":null,"retcode":500,"status":"failed","wording":"参数错误"}`))
} else {
dv := grabReSouData(sum)
json.NewEncoder(writer).Encode(dv)
}
// fmt.Fprintf(writer, `{"code":0}`)
} else {
//接收GET请求
query := request.URL.Query()
if query.Get("sum") != "" {
sum, err := strconv.Atoi(query.Get("sum"))
if err != nil {
writer.WriteHeader(http.StatusInternalServerError)
writer.Write([]byte(`{"data":null,"retcode":500,"status":"failed","wording":"参数错误"}`))
} else {
dv := grabReSouData(sum)
json.NewEncoder(writer).Encode(dv)
}
// fmt.Fprintf(writer, `{"code":0}`)
} else {
dv := grabReSouData(999)
json.NewEncoder(writer).Encode(dv)
}
}
}
//默认首页
func handleIndex(writer http.ResponseWriter, request *http.Request) {
writer.WriteHeader(http.StatusNotFound)
writer.Write([]byte(`{"data":null,"retcode":404,"status":"failed","wording":"API不存在"}`))
//用来返回html的
// t, _ := template.ParseFiles("index.html")
// t.Execute(writer, nil)
}
//CLI帮助
func inCliValue() (string, string) {
app := cli.NewApp()
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "p",
Value: "8082",
Usage: "server port",
},
cli.StringFlag{
Name: "httpsP",
Value: "8083",
Usage: "https server port",
},
}
p := ""
sp := ""
app.Action = func(c *cli.Context) error {
if c.NArg() > 0 {
fmt.Println("您想做什么?")
}
if c.String("p") != "" {
p = c.String("p")
sp = c.String("httpsP")
} else {
p = "8082"
sp = "8083"
}
return nil
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
if p == "" || sp == "" {
os.Exit(0)
}
return p, sp
}
func main() {
var group errgroup.Group
lmt := tollbooth.NewLimiter(30, nil)
// Set a custom message.
lmt.SetMessage("")
// Set a custom content-type.
lmt.SetMessageContentType("text/json; charset=utf-8")
lmt.SetOnLimitReached(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
w.Write([]byte(`{"data":null,"retcode":403,"status":"failed","wording":"请求过于频繁,请稍后重试"}`))
})
port, Sport := inCliValue()
fmt.Println("Running at port " + port + ",https port " + Sport + " ...")
fmt.Println("Other options input -h")
http.Handle("/", tollbooth.LimitFuncHandler(lmt, handleIndex))
http.Handle("/resou", tollbooth.LimitFuncHandler(lmt, handleReSouGetIsPost))
group.Go(func() error {
return http.ListenAndServe(":"+port, nil)
})
group.Go(func() error {
return http.ListenAndServeTLS(":"+Sport, "cert.pem", "key.pem", nil)
})
if err := group.Wait(); err != nil {
log.Fatal(err)
}
}