0

Is there any way to serve multiple directory using fasthttp framework? I wrote the below code for the same purpose. But, this code is not working as I expected. When I access localhost:8080/path1, It throws error and warnings,

Cannot open requested path

2017/10/13 16:57:01 0.977 #0000000100000001 - 127.0.0.1:8080<->127.0.0.1:48870 - GET http://localhost:8080/path1 - cannot open file "/home/test/path1": open /home/test/path1/path1: no such file or directory

I don't know how this url(/home/test/path1) redirects to (/home/test/path1/path1). What is wrong with the below code ?

requestHandler := func(ctx *fasthttp.RequestCtx) {
        var fs fasthttp.FS
        switch string(ctx.Path()) {
        case "/path1":
            fs = fasthttp.FS{
                Root:       "/home/test/path1",
                IndexNames: []string{"index.html"},
            }
        case "/path2":
            fs = fasthttp.FS{
                Root:       "/home/test/path2",
                IndexNames: []string{"index.html"},
            }
        }
        fsHandler := fs.NewRequestHandler()
        fsHandler(ctx)
    }

    if err := fasthttp.ListenAndServe(":8080", requestHandler); err != nil {
        fmt.Println("error in ListenAndServe: %s", err)
    }
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
sprabhakaran
  • 1,615
  • 5
  • 20
  • 36
  • Possible duplicate of [Where does Go web server look for the files](https://stackoverflow.com/questions/46093251/where-does-go-web-server-look-for-the-files) – Jonathan Hall Oct 13 '17 at 13:15

1 Answers1

1

Nothing is wrong, works exactly as you wrote it: Root of webserver: /home/test/path1. You request http://bla/path1. This in turn translates into: http://bla/ -> /home/path/path1/index.html. http://bla/path1 -> /home/path/path1/path1/index.html.

Ow yeah, in case of serving 2 directories - yes you can, just as any other normal HTTP server would, they just need to have the same Root. Otherwise look into virtual hosts support.

favoretti
  • 29,299
  • 4
  • 48
  • 61
  • 1
    The default golang's http server has solved this problem - https://stackoverflow.com/questions/43600768/multiple-dir-serving-is-not-working/43600923#43600923 - FYI – sprabhakaran Oct 13 '17 at 12:09
  • The default golang's HTTP server implementation in that question is completely different from what are you doing code-wise in this example. There you have 2 different handler instances. Here you want to serve 2 different directories with 1 handler. – favoretti Oct 13 '17 at 12:11