diff --git a/example_test.go b/example_test.go index 075107b02702e381b7607cf745a367be04a60591..666914d2ef2dada132c68f5679773c522145c051 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) +}