Skip to content
This repository has been archived by the owner on Apr 23, 2023. It is now read-only.

Commit

Permalink
playground: serve 404 for non-existent pages
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
dmitshur authored and matfax committed Oct 8, 2018
1 parent 3afd4bd commit f5e96ba
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
6 changes: 6 additions & 0 deletions edit.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
6 changes: 4 additions & 2 deletions server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package main

import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net/http"
Expand Down Expand Up @@ -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 {
Expand All @@ -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},
Expand Down

0 comments on commit f5e96ba

Please sign in to comment.