We can customize the handling of status codes specified by WebServer, for example, for common errors like 404/403/500
, we can display custom error messages, page content, or redirect to a specific page.
The related methods are as follows:
func (s *Server) BindStatusHandler(status int, handler HandlerFunc)
func (s *Server) BindStatusHandlerByMap(handlerMap map[int]HandlerFunc)
func (d *Domain) BindStatusHandler(status int, handler HandlerFunc)
func (d *Domain) BindStatusHandlerByMap(handlerMap map[int]HandlerFunc)
As we can see, we can use BindStatusHandler
or BindStatusHandlerByMap
to implement custom callback handling for specified status codes, and this feature also supports binding to specific domain names. Let’s look at a few simple examples.
Basic Usage
package main
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
func main() {
s := g.Server()
s.BindHandler("/", func(r *ghttp.Request){
r.Response.Writeln("halo world!")
})
s.BindStatusHandler(404, func(r *ghttp.Request){
r.Response.Writeln("This is customized 404 page")
})
s.SetPort(8199)
s.Run()
}
After execution, when we visit an unbound route page, such as http://127.0.0.1:8199/test, we can see the page shows our expected return result: This is customized 404 page
.
Moreover, the common way of handling web page request error status codes is to guide users to a specific error page. Therefore, in the status code callback handling function, we can use the r.RedirectTo
method to perform page redirection, as shown in the following example:
package main
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
func main() {
s := g.Server()
s.BindHandler("/status/:status", func(r *ghttp.Request) {
r.Response.Write("woops, status ", r.Get("status"), " found")
})
s.BindStatusHandler(404, func(r *ghttp.Request){
r.Response.RedirectTo("/status/404")
})
s.SetPort(8199)
s.Run()
}
After execution, when we manually access a non-existent page through the browser, such as http://127.0.0.1:8199/test, we can see the page is redirected to http://127.0.0.1:8199/status/404, and the page returns the content: woops, status 404 found
Batch Settings
package main
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
func main() {
s := g.Server()
s.BindStatusHandlerByMap(map[int]ghttp.HandlerFunc {
403 : func(r *ghttp.Request){r.Response.Writeln("403")},
404 : func(r *ghttp.Request){r.Response.Writeln("404")},
500 : func(r *ghttp.Request){r.Response.Writeln("500")},
})
s.SetPort(8199)
s.Run()
}
As we can see, we can use the BindStatusHandlerByMap
method for batch settings of custom status codes. After the example program is executed, when the service API returns status codes 403/404/500
, the API will return the corresponding status code number.
Precautions
If content output is involved in custom status code handling methods, it’s often necessary to use r.Response.ClearBuffer()
to clear the original buffered output content.