drxp993551 2018-07-11 01:10
浏览 235
已采纳

如何使用go / golang中的FileServer函数将文件提供到特定的url路径

I need to serve an html file to localhost:8080/lvlione but the FileServer function in golang doesn't seem to work.

Here is main.go:

package main

import (
    "log"      //logging that the server is running and other stuff
    "net/http" //serving files and stuff
)

func main() {
    //servemux
    server := http.NewServeMux()

    //handlers that serve the home html file when called
    fs := http.FileServer(http.Dir("./home"))
    os := http.FileServer(http.Dir("./lvlone")) //!!this is what is broken!!

    //handles paths by serving correct files
    //there will be if statements down here that check if someone has won or not soon
    server.Handle("/", fs)
    server.Handle("/lvlione", os)

    //logs that server is Listening
    log.Println("Listening...")
    //starts server
    http.ListenAndServe(":8080", server)
}

There is a folder in this directory called lvlone with one file in it (index.html). When I point my browser to localhost:8080/lvlione it returns 404, but when it is pointed to localhost:8080 it returns the correct file.

  • 写回答

1条回答 默认 最新

  • dongshai2022 2018-07-11 01:32
    关注

    You need to call http.StripPrefix to remove the extra lvlone from the directory path.

          server.Handle("/lvlone/", http.StripPrefix("/lvlone/", os))
    

    By default the http.FileServer assumes the path given to it is the root path, and appends the URL to it. If it is to serve a subdirectory of the virtual path, then that needs to be stripped from the path.

    And note that you need to have the trailing slashes in both places.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度