0

While integrating hCaptcha into my golang (go-fiber) project I followed this process:

<!-- index.html -->
<html>

<head>
  <title>hCaptcha Demo</title>
  <script src="https://hcaptcha.com/1/api.js" async defer></script>
</head>

<body>
  <form action="/page" method="POST">
    <input type="text" name="email" placeholder="Email" />
    <input type="password" name="password" placeholder="Password" />
    <div class="h-captcha" data-sitekey="HCAPTCHA_SITE_KEY"></div>
    <br />
    <input type="submit" value="Submit" />
  </form>
</body>

</html>

And on golang the back-end:

func HandleCaptcha(responseToken string) {
    err := godotenv.Load()
    if err != nil {
        log.Fatalf("Error occured loading .env. Err: %s", err)
    }

    data := map[string]string{
        "secret":   os.Getenv("HCAPTCHA_SECRET_KEY"),
        "response": responseToken, // form.Value["h-captcha-response"][0]
        // "remoteip": "ip-address-of-the-user",
    }
    json_data, err := json.Marshal(data)
    if err != nil {
        log.Fatal(err)
    }

    resp, err := http.Post(
        "https://hcaptcha.com/siteverify",
        "application/x-www-form-urlencoded",
        bytes.NewBuffer(json_data),
    )

    if err != nil {
        log.Fatal(err)
    }

    var res map[string]interface{}
    json.NewDecoder(resp.Body).Decode(&res)
    fmt.Println(res["json"])

    if !res["success"].(bool) {
        panic(res["error-codes"].([]interface{}))
    }
}

At this point I get an error:

<nil>
panic: ([]interface {}) 0xc000012c78

goroutine 6 [running]:
main.HandleCaptcha({0xc0001f7300, 0x103e})
        captcha.go:45 +0x3d7

I am not sure if I am on the right path. Is the problem related to the way I send the solution or handle the response? I couldn't find official documentation specifically for Golang or even a proper blog post related to this topic. btw, at the moment I try to avoid using kataras' package.

Eziz Durdyyev
  • 1,110
  • 2
  • 16
  • 34
  • You're sending JSON encoded data to the server at hcaptcha.com but say it's application/x-www-form-urlencoded. Have you looked at the response body? It probably tells you why the verification didn't work. Also, don't ignore the error returned by json.Decoder.Decode. – Peter Oct 17 '22 at 14:45

1 Answers1

0

just print error-codes's structure, find whether is List type.

fmt.Printf("error-codes: %+v\n",res["error-codes"])

you can define struct of response, like this:

type Resp struct{
    Json map[string]interface{} `json:"json"`
    ErrorCodes []string `json:"error_codes"` //maybe string list i guess
    Success bool `json:"success"`
}
naijeux
  • 26
  • 4