justcaptcha/cmd/justcaptchad/main.go

80 lines
1.7 KiB
Go
Raw Normal View History

package main
import (
"flag"
"fmt"
"justcaptcha/internal/captcha"
"justcaptcha/internal/handlers"
"justcaptcha/pkg/server"
"log"
"net/netip"
"os"
"os/signal"
"strings"
"syscall"
"time"
)
var listenAddress *string = flag.String("listen", "/var/run/captcha/c.sock", "listen address (ip:port|unix_path)")
var captchaExpire *time.Duration = flag.Duration("expire", 5*time.Minute, "CAPTCHA expiration in format XX{s,m,h}, e.g. 5m, 300s")
var showVersion *bool = flag.Bool("v", false, "show version")
func main() {
flag.Parse()
log.SetFlags(0)
if *showVersion {
fmt.Println("justcaptchad ver. 1.0\nCopyright (c) 2022 Alexander \"Arav\" Andreev <me@arav.top>")
return
}
defer func() {
if !strings.ContainsRune(*listenAddress, ':') {
os.Remove(*listenAddress)
}
}()
captcha.Init(*captchaExpire)
hand := handlers.New(*captchaExpire)
srv := server.NewHttpServer()
srv.GET("/", hand.New)
srv.POST("/:captcha", hand.Solve)
srv.GET("/:captcha", hand.IsSolved)
srv.GET("/:captcha/image", hand.Image)
var network string
if !strings.ContainsRune(*listenAddress, ':') {
network = "unix"
} else {
ap, err := netip.ParseAddrPort(*listenAddress)
if err != nil {
log.Fatalln(err)
}
if !ap.IsValid() {
log.Fatalln("ip and/or port provided are not valid")
}
if ap.Addr().Is4() {
network = "tcp4"
} else if ap.Addr().Is6() {
network = "tcp6"
}
}
if err := srv.Start(network, *listenAddress); err != nil {
log.Fatalln("failed to start a server:", err)
}
doneSignal := make(chan os.Signal, 1)
signal.Notify(doneSignal, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
<-doneSignal
if err := srv.Stop(); err != nil {
log.Fatalln("failed to properly shutdown a server:", err)
}
}