README.md
Rendering markdown...
package main
import (
"fmt"
"html/template"
"log/slog"
"net/http"
"github.com/justinas/alice"
"github.com/justinas/nosurf"
)
var indexHtml = template.Must(template.New("index").Parse(`
<!doctype html>
<body>
Hi, I'm the target!
</body>
`))
func nosurfConstructor(h http.Handler) http.Handler {
n := nosurf.New(h)
n.SetFailureHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
slog.Info("Request blocked by nosurf", "reason", nosurf.Reason(r))
w.WriteHeader(403)
fmt.Fprintf(w, "Request blocked by nosurf: %v", nosurf.Reason(r))
}))
return n
}
func main() {
m := http.NewServeMux()
m.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
err := indexHtml.Execute(w, struct {
Token string
}{
nosurf.Token(r),
})
if err != nil {
panic(err)
}
})
m.HandleFunc("POST /mutate", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Mutating request successful."))
})
handler := alice.New(nosurfConstructor).Then(m)
if err := http.ListenAndServe(":5000", handler); err != nil {
panic(err)
}
}