1. 定义404页面
在Go语言中,我们可以通过自定义HTTP处理程序来定义404错误页面。首先,我们需要创建一个实现`http.Handler`接口的结构体,并在其中定义自己的ServeHTTP方法。```go type NotFoundHandler struct{} func (h NotFoundHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "404 - Page not found") } ```
上述代码创建了一个名为`NotFoundHandler`的结构体,并给其添加了一个名为`ServeHTTP`的方法。在该方法中,我们首先使用`http.StatusNotFound`设置了响应头的状态码为404。然后,我们使用`fmt.Fprintf`向响应写入了一个简单的404错误消息。2. 处理404错误
现在我们已经定义了404错误页面,接下来需要将其应用到我们的Web应用程序中。我们可以使用`http.NotFound`函数将`NotFoundHandler`类型转换为`http.Handler`接口,并将其传递给我们的HTTP服务器。```go func main() { router := http.NewServeMux() router.Handle("/", NotFoundHandler{}) log.Fatal(http.ListenAndServe(":8080", router)) } ```
上述代码创建了一个HTTP服务器,并将根路径"/"的处理程序设置为我们之前定义的`NotFoundHandler`。最后,我们使用`http.ListenAndServe`函数启动服务器。3. 自定义404页面内容
除了简单的404错误消息外,我们还可以通过自定义HTML模板来创建更具有吸引力的404错误页面。在Go语言中,我们可以使用`html/template`包来处理HTML模板。 首先,我们需要创建一个包含404页面内容的HTML文件。文件可以包含任何您想要展示的信息,例如页面标题、友好的错误消息和指向主页的链接等。404.html:
```html
404 - Page not found
The page you are looking for does not exist. Please check the URL or go back to the homepage.
``` 然后,我们可以在`NotFoundHandler`的`ServeHTTP`方法中使用`template.ParseFiles`函数来解析该HTML文件,并将数据渲染到模板中。```go type NotFoundHandler struct { tpl *template.Template } func (h NotFoundHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) h.tpl.Execute(w, nil) } func main() { tpl, err := template.ParseFiles("404.html") if err != nil { log.Fatal(err) } router := http.NewServeMux() router.Handle("/", NotFoundHandler{tpl}) log.Fatal(http.ListenAndServe(":8080", router)) } ```
在上述代码中,我们将`template.ParseFiles`函数用于解析404.html文件,并将其赋值给`NotFoundHandler`结构体的`tpl`字段。接下来,在`ServeHTTP`方法中,我们使用`Execute`方法将模板渲染到`http.ResponseWriter`中。