2021-01-17 21:46:25 +08:00
|
|
|
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
2018-05-04 14:35:20 +08:00
|
|
|
//
|
|
|
|
// This Source Code Form is subject to the terms of the MIT License.
|
|
|
|
// If a copy of the MIT was not distributed with this file,
|
2019-02-02 16:18:25 +08:00
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
2018-05-04 14:35:20 +08:00
|
|
|
|
|
|
|
package ghttp
|
|
|
|
|
|
|
|
import (
|
2019-06-19 09:06:52 +08:00
|
|
|
"fmt"
|
2018-05-04 14:35:20 +08:00
|
|
|
)
|
|
|
|
|
2020-05-09 19:19:42 +08:00
|
|
|
// getStatusHandler retrieves and returns the handler for given status code.
|
2020-11-25 16:37:41 +08:00
|
|
|
func (s *Server) getStatusHandler(status int, r *Request) []HandlerFunc {
|
2021-09-19 10:01:09 +08:00
|
|
|
domains := []string{r.GetHost(), DefaultDomainName}
|
2019-06-19 09:06:52 +08:00
|
|
|
for _, domain := range domains {
|
|
|
|
if f, ok := s.statusHandlerMap[s.statusHandlerKey(status, domain)]; ok {
|
|
|
|
return f
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
2018-05-04 14:35:20 +08:00
|
|
|
}
|
|
|
|
|
2020-11-25 16:37:41 +08:00
|
|
|
// addStatusHandler sets the handler for given status code.
|
2021-10-21 18:22:47 +08:00
|
|
|
// The parameter `pattern` is like: domain#status
|
2020-11-25 16:37:41 +08:00
|
|
|
func (s *Server) addStatusHandler(pattern string, handler HandlerFunc) {
|
|
|
|
if s.statusHandlerMap[pattern] == nil {
|
|
|
|
s.statusHandlerMap[pattern] = make([]HandlerFunc, 0)
|
|
|
|
}
|
|
|
|
s.statusHandlerMap[pattern] = append(s.statusHandlerMap[pattern], handler)
|
2018-05-04 14:35:20 +08:00
|
|
|
}
|
|
|
|
|
2020-05-09 19:19:42 +08:00
|
|
|
// statusHandlerKey creates and returns key for given status and domain.
|
2019-06-19 09:06:52 +08:00
|
|
|
func (s *Server) statusHandlerKey(status int, domain string) string {
|
|
|
|
return fmt.Sprintf("%s#%d", domain, status)
|
2018-05-04 14:35:20 +08:00
|
|
|
}
|
|
|
|
|
2020-05-09 19:19:42 +08:00
|
|
|
// BindStatusHandler registers handler for given status code.
|
2019-06-19 09:06:52 +08:00
|
|
|
func (s *Server) BindStatusHandler(status int, handler HandlerFunc) {
|
2021-09-19 10:01:09 +08:00
|
|
|
s.addStatusHandler(s.statusHandlerKey(status, DefaultDomainName), handler)
|
2018-05-04 14:35:20 +08:00
|
|
|
}
|
|
|
|
|
2020-05-09 19:19:42 +08:00
|
|
|
// BindStatusHandlerByMap registers handler for given status code using map.
|
2019-06-19 09:06:52 +08:00
|
|
|
func (s *Server) BindStatusHandlerByMap(handlerMap map[int]HandlerFunc) {
|
|
|
|
for k, v := range handlerMap {
|
|
|
|
s.BindStatusHandler(k, v)
|
|
|
|
}
|
|
|
|
}
|