5

Using reCAPTCHA with Go

 3 years ago
source link: https://sj14.gitlab.io/post/2020/03-21-go-recaptcha/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
2020-03-21

See the repository for the current version!

Installation

1
go get -u github.com/sj14/recaptcha

Usage

The result will always return an error when any kind of failure occured, thus only checking the error is sufficient.

reCAPTCHA v2

See reCAPTCHA v2 docs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<html>
  <head>
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
  </head>
  <body>
    <form action="?" method="POST">
      <div class="g-recaptcha" data-sitekey="<YOUR_SITE_KEY>"></div>
      <br/>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>
1
2
3
4
5
result, err := recaptcha.VerifyV2(recaptchaSecret, httpRequest)
if err != nil {
    log.Fatalf("recaptcha failed: %v\n", err)
}
// result is not necessary to check, only required for more details

reCAPTCHA v3

See reCAPTCHA v3 docs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<html>
  <head>
    <script src="https://www.google.com/recaptcha/api.js?render=<YOUR_SITE_KEY>"></script>
    <script>
    grecaptcha.ready(function () {
        grecaptcha.execute('<YOUR_SITE_KEY>', { action: 'register' }).then(function (token) {
            var recaptchaResponse = document.getElementById('g-recaptcha-response');
            recaptchaResponse.value = token;
        });
    });
</script>
</head>
<body>
    <form method="POST" action="/register">
        <input type="hidden" name="g-recaptcha-response" id="g-recaptcha-response">
        <input type="submit" value="Submit">
    </form>
</body>

Without options:

1
2
3
4
5
result, err := recaptcha.VerifyV3(recaptchaSecret, httpRequest)
if err != nil {
    log.Fatalf("recaptcha failed: %v\n", err)
}
// result is not necessary to check, only required for more details

With options:

1
2
3
4
5
6
7
// The default action is empty ("") and thus not checked.
// The default minimum required score is 0.5
result, err := recaptcha.VerifyV3(recaptchaSecret, httpRequest, recaptcha.Action("register"), recaptcha.MinScore(0.7))
if err != nil {
    log.Fatalf("recaptcha failed: %v\n", err)
}
// result is not necessary to check, only required for more details

Shoulders

This package is based on the work of Adam Ng and I highly support his appeal:

IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK