playground: serve 404 for non-existent pages
The server.handleEdit handler is being registered to handle the "/"
pattern. Its code checks if the request URL path has a "/p/" prefix,
and otherwise assumes it's the index page. There's no check if it's
some other unsupported URL. As a result, any URL that isn't handled
elsewhere serves the index page. For example:
https://play.golang.org/foobarbaz
This change fixes that so non-existent pages return a 404 Not Found
error instead.
Also use context.Background() instead of a nil context in a test,
per the context package instructions.
Change-Id: I4c43492397a6f71bffc1e6a657ff2a523a245f94
Reviewed-on: https://go-review.googlesource.com/129795
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
diff --git a/edit.go b/edit.go
index b69c1c0..81923e4 100644
--- a/edit.go
+++ b/edit.go
@@ -32,6 +32,12 @@
return
}
+ // Serve 404 for /foo.
+ if r.URL.Path != "/" && !strings.HasPrefix(r.URL.Path, "/p/") {
+ http.NotFound(w, r)
+ return
+ }
+
snip := &snippet{Body: []byte(hello)}
if strings.HasPrefix(r.URL.Path, "/p/") {
if !allowShare(r) {
diff --git a/server_test.go b/server_test.go
index 0c17407..8621742 100644
--- a/server_test.go
+++ b/server_test.go
@@ -5,6 +5,7 @@
import (
"bytes"
+ "context"
"fmt"
"io/ioutil"
"net/http"
@@ -42,8 +43,8 @@
id := "bar"
barBody := []byte("Snippy McSnipface")
snip := &snippet{Body: barBody}
- if err := s.db.PutSnippet(nil, id, snip); err != nil {
- t.Fatalf("s.dbPutSnippet(nil, %+v, %+v): %v", id, snip, err)
+ if err := s.db.PutSnippet(context.Background(), id, snip); err != nil {
+ t.Fatalf("s.dbPutSnippet(context.Background(), %+v, %+v): %v", id, snip, err)
}
testCases := []struct {
@@ -54,6 +55,7 @@
respBody []byte
}{
{"foo.play.golang.org to play.golang.org", "https://foo.play.golang.org", http.StatusFound, map[string]string{"Location": "https://play.golang.org"}, nil},
+ {"Non-existent page", "https://play.golang.org/foo", http.StatusNotFound, nil, nil},
{"Unknown snippet", "https://play.golang.org/p/foo", http.StatusNotFound, nil, nil},
{"Existing snippet", "https://play.golang.org/p/" + id, http.StatusOK, nil, nil},
{"Plaintext snippet", "https://play.golang.org/p/" + id + ".go", http.StatusOK, nil, barBody},