Skip to content

Commit e8f5bc8

Browse files
committedFeb 21, 2020
Add Example_crossOrigin
Closes #194
1 parent c62c0dc commit e8f5bc8

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
 

‎example_test.go

+28
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"context"
77
"log"
88
"net/http"
9+
"net/url"
910
"time"
1011

1112
"nhooyr.io/websocket"
@@ -115,3 +116,30 @@ func Example_writeOnly() {
115116
err := http.ListenAndServe("localhost:8080", fn)
116117
log.Fatal(err)
117118
}
119+
120+
// This example demonstrates how to safely accept cross origin WebSockets
121+
// from the origin example.com.
122+
func Example_crossOrigin() {
123+
fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
124+
origin := r.Header.Get("Origin")
125+
if origin != "" {
126+
u, err := url.Parse(origin)
127+
if err != nil || u.Host != "example.com" {
128+
http.Error(w, "bad origin header", http.StatusForbidden)
129+
return
130+
}
131+
}
132+
133+
c, err := websocket.Accept(w, r, &websocket.AcceptOptions{
134+
InsecureSkipVerify: true,
135+
})
136+
if err != nil {
137+
log.Println(err)
138+
return
139+
}
140+
c.Close(websocket.StatusNormalClosure, "cross origin WebSocket accepted")
141+
})
142+
143+
err := http.ListenAndServe("localhost:8080", fn)
144+
log.Fatal(err)
145+
}

0 commit comments

Comments
 (0)
Please sign in to comment.