]> Cypherpunks repositories - gostls13.git/commitdiff
net/http: add example for CrossOriginProtection
authorBracken Dawson <abdawson@gmail.com>
Thu, 12 Jun 2025 08:30:28 +0000 (10:30 +0200)
committerGopher Robot <gobot@golang.org>
Mon, 11 Aug 2025 19:16:10 +0000 (12:16 -0700)
It's not immediately appaerent that a method must
be used to wrap the handler, so add a basic
example to guide users to the right API.

Fixes #74121

Change-Id: I23fc3dff6fff9bf4eb29c099bc77da8c99620671
Reviewed-on: https://go-review.googlesource.com/c/go/+/681256
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Sean Liao <sean@liao.dev>
Auto-Submit: Sean Liao <sean@liao.dev>
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
src/net/http/example_test.go

index f40273f14a2a24bc7b30ebbda4febdbae48142fb..acb96bba5178c85e574c74b756586c60aa977310 100644 (file)
@@ -12,6 +12,7 @@ import (
        "net/http"
        "os"
        "os/signal"
+       "time"
 )
 
 func ExampleHijacker() {
@@ -221,3 +222,22 @@ func ExampleProtocols_http1or2() {
        }
        res.Body.Close()
 }
+
+func ExampleCrossOriginProtection() {
+       mux := http.NewServeMux()
+
+       mux.HandleFunc("/hello", func(w http.ResponseWriter, req *http.Request) {
+               io.WriteString(w, "request allowed\n")
+       })
+
+       srv := http.Server{
+               Addr:         ":8080",
+               ReadTimeout:  15 * time.Second,
+               WriteTimeout: 15 * time.Second,
+               // Use CrossOriginProtection.Handler to block all non-safe cross-origin
+               // browser requests to mux.
+               Handler: http.NewCrossOriginProtection().Handler(mux),
+       }
+
+       log.Fatal(srv.ListenAndServe())
+}