-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
49 lines (44 loc) · 1.16 KB
/
handlers.go
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
package main
import (
"fmt"
"github.com/gorilla/mux"
"html/template"
"net/http"
)
type Handlers struct {
Template *template.Template
}
func serve() {
handlers := &Handlers{Template: initTemplate()}
srv := http.Server{
Addr: ":2020",
Handler: handlers.GetRoutes(),
}
fmt.Printf("Starting HTTP server on port %s\n", srv.Addr)
if err := srv.ListenAndServe(); err != nil {
panic(err)
}
}
func (h *Handlers) GetRoutes() *mux.Router {
r := mux.NewRouter()
r.HandleFunc("/contact", h.contactFormHandler).
Methods(http.MethodPost, http.MethodOptions)
r.Use(CORSMethodMiddleware("/contact"))
return r
}
func CORSMethodMiddleware(route string) mux.MiddlewareFunc {
return func(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost && r.RequestURI == route {
for key, value := range map[string]string{
"Access-Control-Allow-Origin": "https://portfolio.mael-91.me",
"Access-Control-Allow-Methods": "OPTIONS, POST",
"Access-Control-Allow-Headers": "Content-Type, Accept",
} {
w.Header().Set(key, value)
}
}
handler.ServeHTTP(w, r)
})
}
}