2017-10-13 33 views
0

有没有什么办法可以使用fasthttp框架来服务多个目录?为了相同的目的,我编写了下面的代码。但是,这段代码并没有像我期望的那样工作。当我访问本地主机:8080/PATH1,它会抛出错误和警告,fasthttp:多个Dir服务器不工作

无法打开请求的路径

2017年10月13日16时57分01秒0.977#0000000100000001 - 127.0。 0.1:8080 < - > 127.0.0.1:48870 - 获取http://localhost:8080/path1 - 无法打开文件 “/家/测试/路径1”: 开 /家/测试/路径1 /路径1: 没有这样的文件或目录

我不知道这个URL(/ home/test/path1)如何重定向到(/ home/test/path1/path1)。下面的代码有什么问题?

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) 
    } 
+0

可能的重复[Where Go Web服务器查找文件](https://stackoverflow.com/questions/46093251/where-does-go-web-server-look-for-the-files) – Flimzy

回答

1

没有什么是错的,正是因为你写它的工作原理: 根web服务器:/home/test/path1。您要求http://bla/path1。这又转化为:http://bla/ - >/home/path/path1/index.htmlhttp://bla/path1 - >/home/path/path1/path1/index.html

是的,如果服务2个目录 - 是的,你可以,就像任何其他普通的HTTP服务器一样,他们只需要有相同的Root。否则看看虚拟主机的支持。

+1

The默认的golang的http服务器已经解决了这个问题 - https://stackoverflow.com/questions/43600768/multiple-dir-serving-is-not-working/43600923#43600923 - FYI – sprabhakaran

+0

该问题中默认的golang的HTTP服务器实现是完全的不同于在这个例子中代码明智的做法。你有2个不同的处理程序实例。这里你想用1个处理程序服务2个不同的目录。 – favoretti