W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
我們可以對(duì)?WebServer
?指定的狀態(tài)碼進(jìn)行自定義處理,例如針對(duì)常見的?404/403/500
?等錯(cuò)誤,我們可以展示自定義的錯(cuò)誤信息、頁面內(nèi)容,或者跳轉(zhuǎn)到一個(gè)特定的頁面。
相關(guān)方法如下:
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)
可以看到,我們可以使用?BindStatusHandler
?或者?BindStatusHandlerMap
?來實(shí)現(xiàn)針對(duì)指定的狀態(tài)碼進(jìn)行自定義的回調(diào)函數(shù)處理,并且該特性也支持針對(duì)特定的域名綁定。我們來看幾個(gè)簡(jiǎn)單的示例。
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 世界!")
})
s.BindStatusHandler(404, func(r *ghttp.Request){
r.Response.Writeln("This is customized 404 page")
})
s.SetPort(8199)
s.Run()
}
執(zhí)行后,我們?cè)L問沒有綁定的路由頁面,例如 http://127.0.0.1:8199/test ,可以看到,頁面顯示了我們期望的返回結(jié)果:?This is customized 404 page
?。
此外,常見的Web頁面請(qǐng)求錯(cuò)誤狀態(tài)碼處理方式,是引導(dǎo)用戶跳轉(zhuǎn)到指定的錯(cuò)誤頁面,因此,在狀態(tài)碼回調(diào)處理函數(shù)中,我們可以使用?r.RedirectTo
?方法來進(jìn)行頁面跳轉(zhuǎn),示例如下:
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()
}
執(zhí)行后,我們手動(dòng)通過瀏覽器訪問一個(gè)不存在的頁面,例如 http://127.0.0.1:8199/test ,可以看到,頁面被引導(dǎo)跳轉(zhuǎn)到了 http://127.0.0.1:8199/status/404 頁面,并且可以看到頁面返回內(nèi)容:?woops, status 404 found
?
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()
}
可以看到,我們可以通過?BindStatusHandlerByMap
?方法對(duì)需要自定義的狀態(tài)碼進(jìn)行批量設(shè)置。該示例程序執(zhí)行后,當(dāng)服務(wù)接口返回的狀態(tài)碼為?403/404/500
?時(shí),接口將會(huì)返回對(duì)應(yīng)的狀態(tài)碼數(shù)字。
在自定義狀態(tài)碼處理方法中如果涉及到內(nèi)容的輸出,往往需要使用?r.Response.ClearBuffer()
?方法將原本緩沖區(qū)的輸出內(nèi)容清空。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: