301 on alias in NotFound
This commit is contained in:
parent
f07a913129
commit
c50d3ee74c
|
@ -0,0 +1,47 @@
|
|||
package main_test
|
||||
|
||||
import (
|
||||
main "h4kor/owl-blogs/cmd/owl-web"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRedirectOnAliases(t *testing.T) {
|
||||
repo := getTestRepo()
|
||||
user, _ := repo.CreateUser("test-1")
|
||||
post, _ := user.CreateNewPost("post-1")
|
||||
|
||||
content := "---\n"
|
||||
content += "title: Test\n"
|
||||
content += "aliases: \n"
|
||||
content += " - /foo/bar\n"
|
||||
content += " - /foo/baz\n"
|
||||
content += "---\n"
|
||||
content += "This is a test"
|
||||
os.WriteFile(post.ContentFile(), []byte(content), 0644)
|
||||
|
||||
// Create Request and Response
|
||||
req, err := http.NewRequest("GET", "/foo/bar", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rr := httptest.NewRecorder()
|
||||
router := main.Router(repo)
|
||||
router.ServeHTTP(rr, req)
|
||||
|
||||
// Check the status code is what we expect.
|
||||
if status := rr.Code; status != http.StatusMovedPermanently {
|
||||
t.Errorf("handler returned wrong status code: got %v want %v",
|
||||
status, http.StatusMovedPermanently)
|
||||
}
|
||||
|
||||
// Check that Location header is set correctly
|
||||
if rr.Header().Get("Location") != post.UrlPath() {
|
||||
t.Errorf("Location header is not set correctly, expected: %v Got: %v",
|
||||
post.UrlPath(),
|
||||
rr.Header().Get("Location"),
|
||||
)
|
||||
}
|
||||
}
|
|
@ -117,3 +117,16 @@ func postMediaHandler(repo owl.Repository) func(http.ResponseWriter, *http.Reque
|
|||
http.ServeFile(w, r, filepath)
|
||||
}
|
||||
}
|
||||
|
||||
func notFoundHandler(repo owl.Repository) func(http.ResponseWriter, *http.Request) {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
path := r.URL.Path
|
||||
aliases, _ := repo.PostAliases()
|
||||
if _, ok := aliases[path]; ok {
|
||||
http.Redirect(w, r, aliases[path].UrlPath(), http.StatusMovedPermanently)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
w.Write([]byte("Not found"))
|
||||
}
|
||||
}
|
||||
|
|
|
@ -16,6 +16,7 @@ func Router(repo owl.Repository) http.Handler {
|
|||
router.GET("/user/:user/", userIndexHandler(repo))
|
||||
router.GET("/user/:user/posts/:post/", postHandler(repo))
|
||||
router.GET("/user/:user/posts/:post/media/*filepath", postMediaHandler(repo))
|
||||
router.NotFound = http.HandlerFunc(notFoundHandler(repo))
|
||||
return router
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue