github.com/zhongdalu/gf@v1.0.0/g/net/ghttp/ghttp_server_status.go (about)

     1  // Copyright 2018 gf Author(https://github.com/zhongdalu/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/zhongdalu/gf.
     6  // 状态码回调函数注册.
     7  
     8  package ghttp
     9  
    10  import (
    11  	"fmt"
    12  )
    13  
    14  // 查询状态码回调函数
    15  func (s *Server) getStatusHandler(status int, r *Request) HandlerFunc {
    16  	domains := []string{r.GetHost(), gDEFAULT_DOMAIN}
    17  	s.statusHandlerMu.RLock()
    18  	defer s.statusHandlerMu.RUnlock()
    19  	for _, domain := range domains {
    20  		if f, ok := s.statusHandlerMap[s.statusHandlerKey(status, domain)]; ok {
    21  			return f
    22  		}
    23  	}
    24  	return nil
    25  }
    26  
    27  // 不同状态码下的回调方法处理
    28  // pattern格式:domain#status
    29  func (s *Server) setStatusHandler(pattern string, handler HandlerFunc) {
    30  	s.statusHandlerMu.Lock()
    31  	s.statusHandlerMap[pattern] = handler
    32  	s.statusHandlerMu.Unlock()
    33  }
    34  
    35  // 生成状态码回调函数map存储键名
    36  func (s *Server) statusHandlerKey(status int, domain string) string {
    37  	return fmt.Sprintf("%s#%d", domain, status)
    38  }
    39  
    40  // 绑定指定的状态码回调函数
    41  func (s *Server) BindStatusHandler(status int, handler HandlerFunc) {
    42  	s.setStatusHandler(s.statusHandlerKey(status, gDEFAULT_DOMAIN), handler)
    43  }
    44  
    45  // 通过map批量绑定状态码回调函数
    46  func (s *Server) BindStatusHandlerByMap(handlerMap map[int]HandlerFunc) {
    47  	for k, v := range handlerMap {
    48  		s.BindStatusHandler(k, v)
    49  	}
    50  }