Skip to content

Commit 3604e0b

Browse files
committed
add timeout for http requests
1 parent a7bb461 commit 3604e0b

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

arcaptcha.go

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,20 @@ import (
66
"fmt"
77
"io/ioutil"
88
"net/http"
9+
"time"
910
)
1011

1112
// arcaptchaApi arcaptcha verify API for captcha V2
12-
const arcaptchaApi = "https://arcaptcha.co/2/siteverify"
13+
const (
14+
arcaptchaApi = "https://arcaptcha.co/2/siteverify"
15+
defaultTimeout = 5 * time.Second
16+
)
1317

1418
type Website struct {
1519
SiteKey string
1620
SecretKey string
21+
22+
client *http.Client
1723
verifyUrl string
1824
}
1925

@@ -38,6 +44,7 @@ func NewWebsite(siteKey, secretKey string) *Website {
3844
return &Website{
3945
SiteKey: siteKey,
4046
SecretKey: secretKey,
47+
client: &http.Client{Timeout: defaultTimeout},
4148
verifyUrl: arcaptchaApi,
4249
}
4350
}
@@ -46,6 +53,10 @@ func (w *Website) SetVerifyUrl(url string) {
4653
w.verifyUrl = url
4754
}
4855

56+
func (w *Website) SetTimeout(timeout time.Duration) {
57+
w.client.Timeout = timeout
58+
}
59+
4960
// Verify calls arcaptcha verify API and returns result.
5061
//
5162
// if an error occurs while sending or receiving the request, returns error.
@@ -57,12 +68,12 @@ func (w *Website) Verify(response string) (VerifyResp, error) {
5768
Response: response,
5869
}
5970
var resp VerifyResp
60-
err := sendRequest(http.MethodPost, w.verifyUrl, data, &resp)
71+
err := w.sendRequest(http.MethodPost, w.verifyUrl, data, &resp)
6172
return resp, err
6273
}
6374

6475
// sendRequest sends http request to 'url' and fill 'resp' by response body
65-
func sendRequest(method, url string, data interface{}, resp interface{}) error {
76+
func (w *Website) sendRequest(method, url string, data, resp interface{}) error {
6677
bin, err := json.Marshal(data)
6778
if err != nil {
6879
return err
@@ -72,7 +83,7 @@ func sendRequest(method, url string, data interface{}, resp interface{}) error {
7283
return err
7384
}
7485
req.Header.Add("Content-Type", "application/json")
75-
res, err := http.DefaultClient.Do(req)
86+
res, err := w.client.Do(req)
7687
if err != nil {
7788
return err
7889
}

examples/example.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ func handleDemo(w http.ResponseWriter, r *http.Request) {
4444
response := r.FormValue("arcaptcha-response")
4545
result, err := website.Verify(response)
4646
if err != nil {
47-
log.Fatal(err)
47+
log.Println(err)
4848
}
4949
if result.Success {
5050
successMsg = "captcha verified"

0 commit comments

Comments
 (0)