-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecaptcha.go
62 lines (53 loc) · 1.42 KB
/
recaptcha.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
// Package recaptcha handles reCaptcha (http://www.google.com/recaptcha) server side validation
package recaptcha
import (
"encoding/json"
"net/http"
"net/url"
"time"
)
// Response from recaptcha
type Response struct {
Success bool `json:"success"`
Score float64 `json:"score"`
Action string `json:"action"`
ChallengeTS time.Time `json:"challenge_ts"`
Hostname string `json:"hostname"`
ErrorCodes []string `json:"error-codes"`
}
// Verifier allows to verify a recaptcha
// You can change the API URL and the http.Client
// (before you start using Verify to avoid race conditions)
type Verifier struct {
privateKey string
APIURL string
Client *http.Client
}
const defaultAPIURL = "https://www.google.com/recaptcha/api/siteverify"
// New instance with the default URL (https://www.google.com/recaptcha/api/siteverify)
func New(privateKey string) Verifier {
return Verifier{
privateKey: privateKey,
APIURL: defaultAPIURL,
Client: &http.Client{Timeout: time.Second * 10},
}
}
// Verify a recaptcha
// this function is thread safe
func (v Verifier) Verify(response string) (Response, error) {
var resp Response
r, err := v.Client.PostForm(
v.APIURL,
url.Values{
"secret": {v.privateKey},
"response": {response},
},
)
if err != nil {
return resp, err
}
if err := json.NewDecoder(r.Body).Decode(&resp); err != nil {
return resp, err
}
return resp, nil
}