-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbing.go
60 lines (53 loc) · 1.58 KB
/
bing.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
package urlsubmitter
import (
"bytes"
"encoding/json"
"errors"
"net/http"
)
// BingSubmitter is a URL submitter for Microsoft's IndexNow API.
type BingSubmitter struct {
API string // API endpoint for submitting URLs to IndexNow.
Key string // Key for the IndexNow API.
KeyLocation string // Location of the key file.
Host string // Host name of the site.
}
// NewBingSubmitter creates a new BingSubmitter with the given parameters.
func NewBingSubmitter(key, keyLocation, host string) *BingSubmitter {
api := "https://api.indexnow.org/IndexNow"
return &BingSubmitter{
API: api,
Key: key,
KeyLocation: keyLocation,
Host: host,
}
}
// SubmitURLs submits the given URLs to Bing's IndexNow API.
// docs: https://www.bing.com/indexnow/getstarted
func (m *BingSubmitter) SubmitURLs(urls []string) (string, error) {
client := &http.Client{}
data := map[string]interface{}{
"host": m.Host,
"key": m.Key,
"keyLocation": m.KeyLocation,
"urlList": urls,
}
jsonData, err := json.Marshal(data)
if err != nil {
return "", err
}
req, err := http.NewRequest("POST", m.API, bytes.NewBuffer(jsonData))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
resp, err := client.Do(req)
if err != nil {
return "", err
}
if resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusAccepted {
// 202 Accepted: 手动在后台提交后再通过API提交就会出现 202
return resp.Status, nil
}
return "", errors.New("invalid response status code:" + resp.Status)
}