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

时间:2015-06-30 22:01:28

标签: http url go

如何从网址栏中删除index.html,例如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)))
    }
}

1 个答案:

答案 0 :(得分:2)

如果网址路径为空,请添加条件以提供index.html:

path := "public"
if req.URL.Path == "/" {
    path += "/index.html"
} else {
    path += req.URL.Path
}

此外,最好使用net/http.ServeFile而不是手动将数据写入输出流(请参阅net/http#ServeContent的文档以了解为什么这是一个好主意)。

还值得注意的是built-in handler for serving files存在。