github.com/gogf/gf/v2@v2.7.4/net/ghttp/ghttp_server_status.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package ghttp 8 9 import ( 10 "fmt" 11 ) 12 13 // getStatusHandler retrieves and returns the handler for given status code. 14 func (s *Server) getStatusHandler(status int, r *Request) []HandlerFunc { 15 domains := []string{r.GetHost(), DefaultDomainName} 16 for _, domain := range domains { 17 if f, ok := s.statusHandlerMap[s.statusHandlerKey(status, domain)]; ok { 18 return f 19 } 20 } 21 return nil 22 } 23 24 // addStatusHandler sets the handler for given status code. 25 // The parameter `pattern` is like: domain#status 26 func (s *Server) addStatusHandler(pattern string, handler HandlerFunc) { 27 if s.statusHandlerMap[pattern] == nil { 28 s.statusHandlerMap[pattern] = make([]HandlerFunc, 0) 29 } 30 s.statusHandlerMap[pattern] = append(s.statusHandlerMap[pattern], handler) 31 } 32 33 // statusHandlerKey creates and returns key for given status and domain. 34 func (s *Server) statusHandlerKey(status int, domain string) string { 35 return fmt.Sprintf("%s#%d", domain, status) 36 } 37 38 // BindStatusHandler registers handler for given status code. 39 func (s *Server) BindStatusHandler(status int, handler HandlerFunc) { 40 s.addStatusHandler(s.statusHandlerKey(status, DefaultDomainName), handler) 41 } 42 43 // BindStatusHandlerByMap registers handler for given status code using map. 44 func (s *Server) BindStatusHandlerByMap(handlerMap map[int]HandlerFunc) { 45 for k, v := range handlerMap { 46 s.BindStatusHandler(k, v) 47 } 48 }