diff --git a/example_test.go b/example_test.go index 075107b0..666914d2 100644 --- a/example_test.go +++ b/example_test.go @@ -6,6 +6,7 @@ import ( "context" "log" "net/http" + "net/url" "time" "nhooyr.io/websocket" @@ -115,3 +116,30 @@ func Example_writeOnly() { err := http.ListenAndServe("localhost:8080", fn) log.Fatal(err) } + +// This example demonstrates how to safely accept cross origin WebSockets +// from the origin example.com. +func Example_crossOrigin() { + fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + origin := r.Header.Get("Origin") + if origin != "" { + u, err := url.Parse(origin) + if err != nil || u.Host != "example.com" { + http.Error(w, "bad origin header", http.StatusForbidden) + return + } + } + + c, err := websocket.Accept(w, r, &websocket.AcceptOptions{ + InsecureSkipVerify: true, + }) + if err != nil { + log.Println(err) + return + } + c.Close(websocket.StatusNormalClosure, "cross origin WebSocket accepted") + }) + + err := http.ListenAndServe("localhost:8080", fn) + log.Fatal(err) +}
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: