From f5e96ba5c9e2cf97daab223e42a65f72cf246155 Mon Sep 17 00:00:00 2001 From: Dmitri Shuralyov Date: Fri, 17 Aug 2018 19:58:32 -0400 Subject: [PATCH] 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 --- edit.go | 6 ++++++ server_test.go | 6 ++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/edit.go b/edit.go index b69c1c0f..81923e4a 100644 --- a/edit.go +++ b/edit.go @@ -32,6 +32,12 @@ func (s *server) handleEdit(w http.ResponseWriter, r *http.Request) { 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 0c174075..86217424 100644 --- a/server_test.go +++ b/server_test.go @@ -5,6 +5,7 @@ package main import ( "bytes" + "context" "fmt" "io/ioutil" "net/http" @@ -42,8 +43,8 @@ func TestEdit(t *testing.T) { 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 @@ func TestEdit(t *testing.T) { 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},