-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
example_test.go
43 lines (34 loc) · 976 Bytes
/
example_test.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
package fcors_test
import (
"io"
"log"
"net/http"
"github.com/jub0bs/fcors"
)
func ExampleAllowAccess() {
mux := http.NewServeMux()
mux.HandleFunc("GET /hello", handleHello) // note: not configured for CORS
// create CORS middleware
cors, err := fcors.AllowAccess(
fcors.FromOrigins("https://example.com"),
fcors.WithMethods(http.MethodGet, http.MethodPost),
fcors.WithRequestHeaders("Authorization"),
)
if err != nil {
log.Fatal(err)
}
api := http.NewServeMux()
api.HandleFunc("GET /users", handleUsersGet)
api.HandleFunc("POST /users", handleUsersPost)
mux.Handle("/api/", http.StripPrefix("/api", cors(api))) // note: method-less pattern here
log.Fatal(http.ListenAndServe(":8080", mux))
}
func handleHello(w http.ResponseWriter, _ *http.Request) {
io.WriteString(w, "Hello, World!")
}
func handleUsersGet(w http.ResponseWriter, _ *http.Request) {
// omitted
}
func handleUsersPost(w http.ResponseWriter, _ *http.Request) {
// omitted
}