go captcha
π§© go captcha is a simple, lightweight library for generating and verifying image-based CAPTCHA codes written in Go.
β¨ Features
- πΌοΈ Generate CAPTCHA images with customizable size and font
- π Built-in encryption for secure token handling
- π§ Optional cache drivers: in-memory or Redis
- βοΈ Flexible configuration using options pattern
- π¨ Zero external dependencies (except
freetype and go-redis/v9)
π Installation
go get github.com/kal72/go-captcha@latest
π§± Usage Example
Basic Example
package main
import (
"fmt"
"github.com/kal72/go-captcha"
)
func main() {
cap := captcha.New("secret-key")
base64Image, text, token, err := cap.Generate()
if err != nil {
panic(err)
}
fmt.Println("text: " + text)
fmt.Println("token: " + token)
fmt.Println("image: " + base64Image)
// Verify
err = cap.Verify(text, token)
if err != nil {
panic("verify failed: " + err.Error())
} else {
fmt.Println("verify success ")
}
}
Using Redis Driver
import (
"github.com/kal72/go-captcha"
"github.com/kal72/go-captcha/driver/redisstore"
)
cap := captcha.New("secret-key",
captcha.WithStore(redisstore.New(redisstore.Config{
Addr: "localhost:6379",
Password: "pass",
DB: 0,
Prefix: "captcha",
})),
)
πΈ Example CAPTCHA Image
Example output image generated:
CAPTCHA Example
βοΈ Configuration Options
| Option |
Description |
WithLength(n int) |
Number of characters in the CAPTCHA code |
WithSize(width, height int) |
CAPTCHA image size in pixels |
WithFontSize(size int) |
Font size in pixels |
WithExpire(seconds int) |
Expiration time in seconds |
WithStore(store Store) |
Use custom store driver (memory, Redis, or your own) |
π§© Custom Driver
To create a custom driver, implement the Store interface:
type Store interface {
Set(key, value string, ttl time.Duration) error
Get(key string) (string, error)
Delete(key string) error
}
Then register it via:
captcha.WithStore(myCustomDriver)
ποΈ Example Directory
See full runnable examples in the examples/ folder:
examples/
βββ basic/
βββ redis/
Run an example:
go run ./examples/basic
π¦ Project Structure
gocaptcha/
βββ captcha.go
βββ config.go
βββ store.go
βββ driver/
β βββ memorystore/
β βββ redisstore/
βββ internal/
β βββ image/
β βββ random/
β βββ assets/
β βββ fonts/
β βββ DejaVuSans-Bold.ttf
βββ examples/