File tree 1 file changed +28
-0
lines changed
1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change 6
6
"context"
7
7
"log"
8
8
"net/http"
9
+ "net/url"
9
10
"time"
10
11
11
12
"nhooyr.io/websocket"
@@ -115,3 +116,30 @@ func Example_writeOnly() {
115
116
err := http .ListenAndServe ("localhost:8080" , fn )
116
117
log .Fatal (err )
117
118
}
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
+ }
You can’t perform that action at this time.
0 commit comments