-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathdiffbot.go
70 lines (62 loc) · 1.7 KB
/
diffbot.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
// Copyright 2014 <chaishushan{AT}gmail.com>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package diffbot
import (
"fmt"
"io/ioutil"
"net/http"
urlPkg "net/url"
)
const (
DefaultServer = `http://api.diffbot.com/v2`
)
// Diffbot uses computer vision, natural language processing
// and machine learning to automatically recognize
// and structure specific page-types.
func Diffbot(method, token, url string, opt *Options) (body []byte, err error) {
return DiffbotServer(DefaultServer, method, token, url, opt)
}
// DiffbotServer like Diffbot function, but support custom server.
func DiffbotServer(server, method, token, url string, opt *Options) (body []byte, err error) {
req, err := http.NewRequest("GET", makeRequestUrl(server, method, token, url, opt), nil)
if err != nil {
return nil, err
}
if opt != nil && opt.CustomHeader != nil {
req.Header = opt.CustomHeader
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
if len(body) != 0 {
var apiError Error
if err = apiError.ParseJson(string(body)); err != nil {
err = &Error{
ErrCode: resp.StatusCode,
ErrMessage: string(body),
}
return
} else {
err = &apiError
return
}
} else {
err = &Error{
ErrCode: resp.StatusCode,
ErrMessage: resp.Status,
}
return
}
}
return
}
func makeRequestUrl(server, method, token, webUrl string, opt *Options) string {
return fmt.Sprintf("%s/%s?token=%s&url=%s%s",
server, method, token, urlPkg.QueryEscape(webUrl), opt.MethodParamString(method),
)
}