File: main.go

package info (click to toggle)
golang-github-gorilla-csrf 1.7.2-1~bpo12%2B1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-backports
  • size: 296 kB
  • sloc: makefile: 60; javascript: 38
file content (66 lines) | stat: -rw-r--r-- 1,582 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// +build ignore

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"
	"time"

	"github.com/gorilla/csrf"
	"github.com/gorilla/handlers"
	"github.com/gorilla/mux"
)

func main() {
	router := mux.NewRouter()

	loggingMiddleware := func(h http.Handler) http.Handler {
		return handlers.LoggingHandler(os.Stdout, h)
	}
	router.Use(loggingMiddleware)

	CSRFMiddleware := csrf.Protect(
		[]byte("place-your-32-byte-long-key-here"),
		csrf.Secure(false),                 // false in development only!
		csrf.RequestHeader("X-CSRF-Token"), // Must be in CORS Allowed and Exposed Headers
	)

	APIRouter := router.PathPrefix("/api").Subrouter()
	APIRouter.Use(CSRFMiddleware)
	APIRouter.HandleFunc("", Get).Methods(http.MethodGet)
	APIRouter.HandleFunc("", Post).Methods(http.MethodPost)

	CORSMiddleware := handlers.CORS(
		handlers.AllowCredentials(),
		handlers.AllowedOriginValidator(
			func(origin string) bool {
				return strings.HasPrefix(origin, "http://localhost")
			},
		),
		handlers.AllowedHeaders([]string{"X-CSRF-Token"}),
		handlers.ExposedHeaders([]string{"X-CSRF-Token"}),
	)

	server := &http.Server{
		Handler:      CORSMiddleware(router),
		Addr:         "localhost:8080",
		ReadTimeout:  60 * time.Second,
		WriteTimeout: 60 * time.Second,
	}

	fmt.Println("starting http server on localhost:8080")
	log.Panic(server.ListenAndServe())
}

func Get(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("X-CSRF-Token", csrf.Token(r))
	w.WriteHeader(http.StatusOK)
}

func Post(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
}