猿问

如何从 golang 中的 url 中删除 index.html 路径

如何index.html从我的 URL 栏中删除,例如localhost:8000/index.html


package main


import (

    "net/http"

    "io/ioutil"

)


func main() {

    http.Handle("/", new(MyHandler))


    http.ListenAndServe(":8000", nil)

}

type MyHandler struct {

    http.Handler

}


func (this *MyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {

    path := "public" + req.URL.Path

    data, err := ioutil.ReadFile(string(path))


    if err == nil {

        w.Write(data)

    } else {

        w.WriteHeader(404)

        w.Write([]byte("404 - " + http.StatusText(404)))

    }

}


白板的微信
浏览 161回答 1
1回答

交互式爱情

如果 URL 路径为空,则添加条件以提供 index.html:path := "public"if req.URL.Path == "/" {    path += "/index.html"} else {    path += req.URL.Path}此外,最好使用net/http.ServeFileover 手动将数据写入输出流(请参阅net/http#ServeContent的文档以了解为什么这是一个好主意)。还值得注意的是,存在用于提供文件的内置处理程序。
随时随地看视频慕课网APP

相关分类

Go
我要回答