如何使用go / golang

时间:2018-07-11 01:10:29

标签: go web

我需要将一个HTML文件提供给localhost:8080/lvlione,但golang中的FileServer函数似乎无法正常工作。

这是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)
}

此目录中有一个名为lvlone的文件夹,其中有一个文件(index.html)。当我将浏览器指向localhost:8080/lvlione时,它将返回404,但是当指向localhost:8080时,它将返回正确的文件。

1 个答案:

答案 0 :(得分:1)

您需要致电http.StripPrefix,以从目录路径中删除多余的lvlone

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

默认情况下,http.FileServer假定给定的路径是根路径,并将URL附加到该路径。如果要提供虚拟路径的子目录,则需要从该路径中删除该子目录。

请注意,两个地方都必须有斜杠。