gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:10:40 30 4
gpt4 key购买 nike

如何从我的 URL 栏中删除 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)))
}
}

最佳答案

添加条件以在 URL 路径为空时提供 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存在。

关于http - 如何从 golang 中的 url 中删除 index.html 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31149304/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com