使用自定义状态代码服务 html 文件
Serve html file with custom status code
我需要一个未找到的自定义 html 页面。这是我尝试过的:
package main
import (
"net/http"
"github.com/julienschmidt/httprouter"
)
func main() {
r := httprouter.New()
r.NotFound = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(404)
http.ServeFile(w, r, "files/not-found.html")
})
http.ListenAndServe(":8000", r)
}
我有行 w.WriteHeader(404)
来确保状态代码是 404,但是上面的代码给出了错误:
http: multiple response.WriteHeader calls
没有行 w.WriteHeader(404)
就没有错误,页面显示正确,但状态代码是 200。我希望它是 404。
内容自己写就可以了
类似于:
r.NotFound = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
contents, err := ioutil.ReadFile("files/not-found.html")
if err != nil {
panic(err) // or do something useful
}
w.WriteHeader(404)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(contents)
})
大卫的回答奏效了,这是另一种方式。
// other header stuff
w.WriteHeader(http.StatusNotFound)
file, err := os.Open("files/not-found.html")
if err != nil {
log.Println(err)
return
}
_, err = io.Copy(w, file)
if err != nil {
log.Println(err)
}
file.Close() // consider defer ^
我需要一个未找到的自定义 html 页面。这是我尝试过的:
package main
import (
"net/http"
"github.com/julienschmidt/httprouter"
)
func main() {
r := httprouter.New()
r.NotFound = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(404)
http.ServeFile(w, r, "files/not-found.html")
})
http.ListenAndServe(":8000", r)
}
我有行 w.WriteHeader(404)
来确保状态代码是 404,但是上面的代码给出了错误:
http: multiple response.WriteHeader calls
没有行 w.WriteHeader(404)
就没有错误,页面显示正确,但状态代码是 200。我希望它是 404。
内容自己写就可以了
类似于:
r.NotFound = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
contents, err := ioutil.ReadFile("files/not-found.html")
if err != nil {
panic(err) // or do something useful
}
w.WriteHeader(404)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(contents)
})
大卫的回答奏效了,这是另一种方式。
// other header stuff
w.WriteHeader(http.StatusNotFound)
file, err := os.Open("files/not-found.html")
if err != nil {
log.Println(err)
return
}
_, err = io.Copy(w, file)
if err != nil {
log.Println(err)
}
file.Close() // consider defer ^