buaazp / fasthttprouter

A high performance fasthttp request router that scales well
http://godoc.org/github.com/buaazp/fasthttprouter
BSD 3-Clause "New" or "Revised" License
876 stars 91 forks source link

Ask: how to rewrite body? #25

Closed kokizzu closed 7 years ago

kokizzu commented 7 years ago

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?

buaazp commented 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))
}
kokizzu commented 7 years ago

Ah but i want to use fasthttp.FSHandler also since it's support caching, rather than rewriting everything.

buaazp commented 7 years ago

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))
}
kokizzu commented 7 years ago

also no, that way i have to list everything i have on public/*/*/* directory (that accesssed through */*/*

buaazp commented 7 years ago

So you need to modify fasthttp.FSHandler or create a private FSHandler for your own logic.

buaazp commented 7 years ago
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))
}