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
872 stars 91 forks source link

file server #37

Closed macpatel40 closed 5 years ago

macpatel40 commented 6 years ago

I'm using Parseglobe and ExecuteTemplate with ctx. However, I need to setup fileserver where each html, css, and img file get their respective header (such as text/html, text/css, image/jpg etc) so that they don't show up as a plain text. I tried the following code but failed. Any help would he appreciated :)

package main

import (
"html/template"
"log"
"github.com/valyala/fasthttp"
)
func init() {
    tpl = template.Must(template.ParseGlob("public/templates/*.html"))
}

func main() {
m := func(ctx *fasthttp.RequestCtx) {
        switch string(ctx.Path()) {
        case "/":
            idx(ctx)
        default:
            ctx.Error("not found", fasthttp.StatusNotFound)
        }

    }
    if err := fasthttp.ListenAndServe(":8081", m); err != nil {
        log.Fatalf("Error in server: %s", err)
    }
}

func idx(ctx *fasthttp.RequestCtx) { 

path := ctx.Path()
    switch {
    case bytes.HasPrefix(path, imgPrefix):
        ctx.SetContentType("image/jpeg")
    case bytes.HasPrefix(path, cssPrefix):
        ctx.SetContentType("text/css")
    default:
        ctx.SetContentType("text/css")
    }

err := tpl.ExecuteTemplate(ctx, "index.html",pd)
    if err != nil {
        log.Println("LOGGED", err)
    //  ctx.Error("Internal server error", ctx.StatusInternalServerError)
        return
    }
erikdubbelboer commented 6 years ago

Not sure why you made this issue with fasthttprouter seen as you're not using this package at all.

I'm guessing imgPrefix and cssPrefix are defined somewhere else otherwise it doesn't even compile.

Your m closure only calls the idx function if the path is exactly / but then the idx function tries to match it with all kinds of paths.

In the idx function sets text/css as default content type while it then always serves a .html file.

buaazp commented 5 years ago

I think this is not a fasthttprouter related issue too. Thanks to @erikdubbelboer .