haisum/recaptcha

Set timeout for requests, don't use DefaultClient

Closed this issue · 1 comments

The DefaultClient in Go's "net/http" package, which is used by http.PostForm, does not have a default timeout, so the request sent to google's servers could hang infinitely. My suggestion is not to use the DefaultClient, and set a sensible timeout (I suppose 10-30 seconds is reasonable.)

diff --git a/recaptcha.go b/recaptcha.go
index a539f6d..2cd970b 100644
--- a/recaptcha.go
+++ b/recaptcha.go
@@ -21,6 +21,7 @@ import (
        "io/ioutil"
        "net/http"
        "net/url"
+       "time"
 )

 // recaptcha.R type represents an object of Recaptcha and has public property Secret,
@@ -45,7 +46,8 @@ var postUrl string = "https://www.google.com/recaptcha/api/siteverify"
 func (r *R) Verify(req http.Request) bool {
        r.lastError = make([]string, 1)
        response := req.PostFormValue("g-recaptcha-response")
-       resp, err := http.PostForm(postUrl,
+       client := &http.Client{Timeout: 20 * time.Second}
+       resp, err := client.PostForm(postUrl,
                url.Values{"secret": {r.Secret}, "response": {response}})
        if err != nil {
                r.lastError = append(r.lastError, err.Error())

Acknowledged. Send me a pull request I will merge after testing. Or I will fix it myself after a few days.