ghttp_server_status.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright GoFrame Author(https://github.com/gogf/gf). 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. package ghttp
  7. import (
  8. "fmt"
  9. )
  10. // getStatusHandler retrieves and returns the handler for given status code.
  11. func (s *Server) getStatusHandler(status int, r *Request) []HandlerFunc {
  12. domains := []string{r.GetHost(), defaultDomainName}
  13. for _, domain := range domains {
  14. if f, ok := s.statusHandlerMap[s.statusHandlerKey(status, domain)]; ok {
  15. return f
  16. }
  17. }
  18. return nil
  19. }
  20. // addStatusHandler sets the handler for given status code.
  21. // The parameter <pattern> is like: domain#status
  22. func (s *Server) addStatusHandler(pattern string, handler HandlerFunc) {
  23. if s.statusHandlerMap[pattern] == nil {
  24. s.statusHandlerMap[pattern] = make([]HandlerFunc, 0)
  25. }
  26. s.statusHandlerMap[pattern] = append(s.statusHandlerMap[pattern], handler)
  27. }
  28. // statusHandlerKey creates and returns key for given status and domain.
  29. func (s *Server) statusHandlerKey(status int, domain string) string {
  30. return fmt.Sprintf("%s#%d", domain, status)
  31. }
  32. // BindStatusHandler registers handler for given status code.
  33. func (s *Server) BindStatusHandler(status int, handler HandlerFunc) {
  34. s.addStatusHandler(s.statusHandlerKey(status, defaultDomainName), handler)
  35. }
  36. // BindStatusHandlerByMap registers handler for given status code using map.
  37. func (s *Server) BindStatusHandlerByMap(handlerMap map[int]HandlerFunc) {
  38. for k, v := range handlerMap {
  39. s.BindStatusHandler(k, v)
  40. }
  41. }