| 1 |
|
| 2 |
|
| 3 |
package main |
| 4 |
|
| 5 |
import ( |
| 6 |
"fmt" |
| 7 |
"log" |
| 8 |
"net/http" |
| 9 |
"os" |
| 10 |
"strings" |
| 11 |
"time" |
| 12 |
|
| 13 |
"github.com/gorilla/csrf" |
| 14 |
"github.com/gorilla/handlers" |
| 15 |
"github.com/gorilla/mux" |
| 16 |
) |
| 17 |
|
| 18 |
func main() { |
| 19 |
router := mux.NewRouter() |
| 20 |
|
| 21 |
loggingMiddleware := func(h http.Handler) http.Handler { |
| 22 |
return handlers.LoggingHandler(os.Stdout, h) |
| 23 |
} |
| 24 |
router.Use(loggingMiddleware) |
| 25 |
|
| 26 |
CSRFMiddleware := csrf.Protect( |
| 27 |
[]byte("place-your-32-byte-long-key-here"), |
| 28 |
csrf.Secure(false), |
| 29 |
csrf.RequestHeader("X-CSRF-Token"), |
| 30 |
) |
| 31 |
|
| 32 |
APIRouter := router.PathPrefix("/api").Subrouter() |
| 33 |
APIRouter.Use(CSRFMiddleware) |
| 34 |
APIRouter.HandleFunc("", Get).Methods(http.MethodGet) |
| 35 |
APIRouter.HandleFunc("", Post).Methods(http.MethodPost) |
| 36 |
|
| 37 |
CORSMiddleware := handlers.CORS( |
| 38 |
handlers.AllowCredentials(), |
| 39 |
handlers.AllowedOriginValidator( |
| 40 |
func(origin string) bool { |
| 41 |
return strings.HasPrefix(origin, "http://localhost") |
| 42 |
}, |
| 43 |
), |
| 44 |
handlers.AllowedHeaders([]string{"X-CSRF-Token"}), |
| 45 |
handlers.ExposedHeaders([]string{"X-CSRF-Token"}), |
| 46 |
) |
| 47 |
|
| 48 |
server := &http.Server{ |
| 49 |
Handler: CORSMiddleware(router), |
| 50 |
Addr: "localhost:8080", |
| 51 |
ReadTimeout: 60 * time.Second, |
| 52 |
WriteTimeout: 60 * time.Second, |
| 53 |
} |
| 54 |
|
| 55 |
fmt.Println("starting http server on localhost:8080") |
| 56 |
log.Panic(server.ListenAndServe()) |
| 57 |
} |
| 58 |
|
| 59 |
func Get(w http.ResponseWriter, r *http.Request) { |
| 60 |
w.Header().Add("X-CSRF-Token", csrf.Token(r)) |
| 61 |
w.WriteHeader(http.StatusOK) |
| 62 |
} |
| 63 |
|
| 64 |
func Post(w http.ResponseWriter, r *http.Request) { |
| 65 |
w.WriteHeader(http.StatusOK) |
| 66 |
} |