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.

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

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序