Skip to content

Commit fa720b9

Browse files
authored
Merge pull request #195 from nhooyr/example-cross-origin
Add Example_crossOrigin
2 parents c62c0dc + e8f5bc8 commit fa720b9

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

example_test.go

Lines changed: 28 additions & 0 deletions
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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy