Closed kokizzu closed 7 years ago
Like this?
func myNotFound(ctx *fasthttp.RequestCtx) {
const (
publicIndex = "./public/index.html"
customIndex = "./custom/index.html"
)
index := publicIndex
if NotExisted(publicIndex) {
index = customIndex
}
body, _ := ioutil.ReadFile(publicIndex)
ctx.Write(body)
ctx.Response.Header.SetContentType("text/html")
}
func main() {
router := fasthttprouter.New()
router.GET("/", Index)
router.NotFound = myNotFound
log.Fatal(fasthttp.ListenAndServe(":8080", router.Handler))
}
Ah but i want to use fasthttp.FSHandler
also since it's support caching, rather than rewriting everything.
How about this?
func myNotFound(ctx *fasthttp.RequestCtx) {
const (
publicIndex = "./public/index.html"
customIndex = "./custom/index.html"
)
if IsExisted(publicIndex) {
ctx.Redirect("/notfound", 301)
return
}
body, _ := ioutil.ReadFile(customIndex)
ctx.Write(body)
ctx.Response.Header.SetContentType("text/html")
}
func main() {
router := fasthttprouter.New()
router.GET("/", Index)
router.GET("/notfound", fasthttp.FSHandler("./public", 0))
router.NotFound = myNotFound
log.Fatal(fasthttp.ListenAndServe(":8080", router.Handler))
}
also no, that way i have to list everything i have on public/*/*/*
directory (that accesssed through */*/*
So you need to modify fasthttp.FSHandler
or create a private FSHandler
for your own logic.
func myNotFound(ctx *fasthttp.RequestCtx) {
const (
public = "./public"
custom = "./custom"
)
uri := string(ctx.RequestURI())
filename := path.Join(public, uri)
if IsExisted(filename) {
ctx.Redirect(path.Join("/notfound", uri), 301)
return
}
filename = path.Join(custom, uri)
body, _ := ioutil.ReadFile(filename)
ctx.Write(body)
ctx.Response.Header.SetContentType("text/html")
}
func main() {
router := fasthttprouter.New()
router.GET("/", Index)
router.GET("/notfound", fasthttp.FSHandler("./public", 0))
router.NotFound = myNotFound
log.Fatal(fasthttp.ListenAndServe(":8080", router.Handler))
}
If I use
router.NotFound = fasthttp.FSHandler("./public", 0)
to handle the static files, but I want to add a custom page if the static file not found, what should I do?