forked from DisposaBoy/GoSublime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
m_pkgdoc.go
114 lines (96 loc) · 1.9 KB
/
m_pkgdoc.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
package main
import (
"bufio"
"bytes"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
type mPkgdoc struct {
Q jString
Path jString
}
type mPkgdocDoc struct {
Path string `json:"path"`
Doc string `json:"doc"`
}
func setupReq(req *http.Request) {
req.Header.Set("User-Agent", "GoSublime")
req.Header.Set("Accept", "text/plain")
}
func mPkgdocFetchDoc(m *mPkgdoc) (interface{}, string) {
res := M{}
path := strings.TrimSpace(m.Path.String())
if path == "" {
return res, "invalid query"
}
req, err := http.NewRequest("GET", "http://godoc.org/"+path, nil)
if err != nil {
return res, errStr(err)
}
setupReq(req)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return res, errStr(err)
}
defer resp.Body.Close()
s, err := ioutil.ReadAll(resp.Body)
if err != nil {
return res, errStr(err)
}
res["doc"] = mPkgdocDoc{
Path: path,
Doc: string(s),
}
return res, ""
}
func mPkgdocSearch(m *mPkgdoc) (interface{}, string) {
res := M{}
s := strings.TrimSpace(m.Q.String())
if s == "" {
return res, "invalid query"
}
req, err := http.NewRequest("GET", "http://godoc.org/?q="+url.QueryEscape(s), nil)
if err != nil {
return res, errStr(err)
}
setupReq(req)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return res, errStr(err)
}
defer resp.Body.Close()
results := []mPkgdocDoc{}
rd := bufio.NewReader(resp.Body)
for {
s, err := rd.ReadBytes('\n')
if err != nil {
break
}
s = bytes.TrimSpace(s)
if len(s) > 0 {
l := bytes.SplitN(s, []byte{' '}, 2)
v := mPkgdocDoc{
Path: string(l[0]),
}
if len(l) == 2 {
v.Doc = string(l[1])
}
results = append(results, v)
}
}
res["results"] = results
return res, ""
}
func (m *mPkgdoc) Call() (interface{}, string) {
if m.Q != "" {
return mPkgdocSearch(m)
}
return mPkgdocFetchDoc(m)
}
func init() {
registry.Register("pkgdoc", func(b *Broker) Caller {
return &mPkgdoc{}
})
}