godoc: fix out-of-bounds panic when serving top-level files

Change-Id: I0ba84bac0c97715c0bc66fdc4c33678341ef140c
Reviewed-on: https://go-review.googlesource.com/53151
Reviewed-by: Chris Broadfoot <cbro@golang.org>
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
diff --git a/godoc/godoc.go b/godoc/godoc.go
index 5c6d982..d6c27d0 100644
--- a/godoc/godoc.go
+++ b/godoc/godoc.go
@@ -461,17 +461,14 @@
 	return "pkg/" + path
 }
 
-// srcToPkgLinkFunc builds an <a> tag linking to
-// the package documentation of relpath.
+// srcToPkgLinkFunc builds an <a> tag linking to the package
+// documentation of relpath.
 func srcToPkgLinkFunc(relpath string) string {
 	relpath = pkgLinkFunc(relpath)
-	if relpath == "pkg/" {
+	relpath = pathpkg.Dir(relpath)
+	if relpath == "pkg" {
 		return `<a href="/pkg">Index</a>`
 	}
-	if i := strings.LastIndex(relpath, "/"); i != -1 {
-		// Remove filename after last slash.
-		relpath = relpath[:i]
-	}
 	return fmt.Sprintf(`<a href="/%s">%s</a>`, relpath, relpath[len("pkg/"):])
 }
 
diff --git a/godoc/godoc_test.go b/godoc/godoc_test.go
index dca1c95..c1d631c 100644
--- a/godoc/godoc_test.go
+++ b/godoc/godoc_test.go
@@ -313,6 +313,8 @@
 	}{
 		{"src/", `<a href="/pkg">Index</a>`},
 		{"src/fmt/", `<a href="/pkg/fmt">fmt</a>`},
+		{"pkg/", `<a href="/pkg">Index</a>`},
+		{"pkg/LICENSE", `<a href="/pkg">Index</a>`},
 	} {
 		if got := srcToPkgLinkFunc(tc.path); got != tc.want {
 			t.Errorf("srcToPkgLinkFunc(%v) = %v; want %v", tc.path, got, tc.want)