Debian Codegraph @

capexample/main.go

raw symbols SCIP
1 // Copyright 2011 Dmitry Chestnykh. All rights reserved.
2 // Use of this source code is governed by a MIT-style
3 // license that can be found in the LICENSE file.
4
5 // example of HTTP server that uses the captcha package.
6 //
7 //nolint:forbidigo
8 package main
9
10 import (
11 "fmt"
12 "io"
13 "log"
14 "net/http"
15 "text/template"
16
17 "code.forgejo.org/go-chi/captcha"
18 )
19
20 var formTemplate = template.Must(template.New("example").Parse(formTemplateSrc))
21
22 func showFormHandler(w http.ResponseWriter, r *http.Request) {
23 if r.URL.Path != "/" {
24 http.NotFound(w, r)
25 return
26 }
27 d := struct {
28 CaptchaID string
29 }{
30 captcha.New(),
31 }
32 if err := formTemplate.Execute(w, &d); err != nil {
33 http.Error(w, err.Error(), http.StatusInternalServerError)
34 }
35 }
36
37 func processFormHandler(w http.ResponseWriter, r *http.Request) {
38 w.Header().Set("Content-Type", "text/html; charset=utf-8")
39 if !captcha.VerifyString(r.FormValue("captchaId"), r.FormValue("captchaSolution")) {
40 _, _ = io.WriteString(w, "Wrong captcha solution! No robots allowed!\n")
41 } else {
42 _, _ = io.WriteString(w, "Great job, human! You solved the captcha.\n")
43 }
44 _, _ = io.WriteString(w, "<br><a href='/'>Try another one</a>")
45 }
46
47 func main() {
48 http.HandleFunc("/", showFormHandler)
49 http.HandleFunc("/process", processFormHandler)
50 http.Handle("/captcha/", captcha.Server(captcha.StdWidth, captcha.StdHeight))
51 fmt.Println("Server is at localhost:8666")
52 if err := http.ListenAndServe("localhost:8666", nil); err != nil {
53 log.Fatal(err)
54 }
55 }
56
57 const formTemplateSrc = `<!doctype html>
58 <head><title>Captcha Example</title></head>
59 <body>
60 <script>
61 function setSrcQuery(e, q) {
62 var src = e.src;
63 var p = src.indexOf('?');
64 if (p >= 0) {
65 src = src.substr(0, p);
66 }
67 e.src = src + "?" + q
68 }
69
70 function reload() {
71 setSrcQuery(document.getElementById('image'), "reload=" + (new Date()).getTime());
72 return false;
73 }
74 </script>
75 <form action="/process" method=post>
76 <p>Type the numbers you see in the picture below:</p>
77 <p><img style="transform: scaleX(-1)" id=image src="/captcha/{{.CaptchaID}}.png" alt="Captcha image"></p>
78 <a href="#" onclick="reload()">Reload</a>
79 <input type=hidden name=captchaId value="{{.CaptchaID}}"><br>
80 <input name=captchaSolution>
81 <input type=submit value=Submit>
82 </form>
83 `