all repos — captcha @ 8b932fcfbb9e93f8dbdef6b8f4eba58448af76c3

Go package captcha implements generation and verification of image and audio CAPTCHAs.

originals/generate.go (view raw)

 1// Generates ../sounds.go from WAVE files
 2package main
 3
 4import (
 5	"fmt"
 6	"os"
 7	"io"
 8	"io/ioutil"
 9	"log"
10	"path"
11)
12
13const headerLen = 44
14
15func writeVar(w io.Writer, b []byte, prefix string) {
16	i := 0
17	for j, v := range b {
18		fmt.Fprintf(w, "0x%02x,", v)
19		i++
20		if i == 11 {
21			fmt.Fprintf(w, "\n")
22			if j != len(b)-1 {
23				fmt.Fprintf(w, prefix)
24			}
25			i = 0
26		} else {
27			fmt.Fprintf(w, " ")
28		}
29	}
30	if i > 0 {
31		fmt.Fprintf(w, "\n")
32	}
33}
34
35func writeFileRep(pcm io.Writer, name, prefix string) {
36	b, err := ioutil.ReadFile(name)
37	if err != nil {
38		log.Fatalf("%s", err)
39	}
40	writeVar(pcm, b[headerLen:], prefix)
41}
42
43func writeSingle(pcm io.Writer, name string) {
44	fmt.Fprintf(pcm, "\nvar %sSound = []byte{\n\t", name)
45	writeFileRep(pcm, name+".wav", "\t")
46	fmt.Fprintf(pcm, "}\n")
47}
48
49func writeNumbers(pcm io.Writer) {
50	fmt.Fprintf(pcm, "var numberSounds = [][]byte{\n")
51	for i := 0; i <= 9; i++ {
52		fmt.Fprintf(pcm, "\t{ // %d\n\t\t", i)
53		writeFileRep(pcm, fmt.Sprintf("%d.wav", i), "\t\t")
54		fmt.Fprintf(pcm, "\t},\n")
55	}
56	fmt.Fprintf(pcm, "}\n")
57}
58
59func main() {
60	pcm, err := os.Create(path.Join("..", "sounds.go"))
61	if err != nil {
62		log.Fatalf("%s", err)
63	}
64	defer pcm.Close()
65	fmt.Fprintf(pcm, `package captcha
66		    
67// This file has been generated from .wav files using generate.go.
68
69var waveHeader = []byte{
70	0x52, 0x49, 0x46, 0x46, 0xdf, 0x0a, 0x00, 0x00, 0x57, 0x41, 0x56, 0x45,
71	0x66, 0x6d, 0x74, 0x20, 0x10, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00,
72	0x40, 0x1f, 0x00, 0x00, 0x40, 0x1f, 0x00, 0x00, 0x01, 0x00, 0x08, 0x00,
73	0x64, 0x61, 0x74, 0x61,
74}
75
76// Byte slices contain raw 8 kHz unsigned 8-bit PCM data (without wav header).
77
78`)
79	writeNumbers(pcm)
80	writeSingle(pcm, "beep")
81}