forked from bunsenapp/go-selenium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_service.go
executable file
·64 lines (49 loc) · 1.29 KB
/
api_service.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
package goselenium
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"errors"
)
type apiServicer interface {
performRequest(string, string, io.Reader) ([]byte, error)
}
type requestError struct {
State string `json:"state"`
Value requestErrorValue `json:"value"`
}
func (r requestError) Error() string {
return fmt.Sprintf("Invalid status code returned, message: %v, information: %v", r.State, r.Value.Message)
}
type requestErrorValue struct {
Message string `json:"localizedMessage"`
}
type seleniumAPIService struct{}
func (a seleniumAPIService) performRequest(url string, method string, body io.Reader) ([]byte, error) {
request, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
client := http.Client{}
resp, err := client.Do(request)
if err != nil {
return nil, fmt.Errorf("%s: an unexpected communication failure occurred, error: %s", method, err.Error())
}
defer resp.Body.Close()
var buf bytes.Buffer
buf.ReadFrom(resp.Body)
r := buf.Bytes()
if resp.StatusCode != 200 {
var reqErr requestError
var errStr string
err := json.Unmarshal(r, &reqErr)
if err == nil {
return nil, &reqErr
}
errStr = fmt.Sprintf("Status code %v returned with no body", resp.StatusCode)
return nil, errors.New(errStr)
}
return r, nil
}