github.com/polarismesh/polaris@v1.17.8/common/conn/hook/conn.go (about)

     1  /**
     2   * Tencent is pleased to support the open source community by making Polaris available.
     3   *
     4   * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
     5   *
     6   * Licensed under the BSD 3-Clause License (the "License");
     7   * you may not use this file except in compliance with the License.
     8   * You may obtain a copy of the License at
     9   *
    10   * https://opensource.org/licenses/BSD-3-Clause
    11   *
    12   * Unless required by applicable law or agreed to in writing, software distributed
    13   * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
    14   * CONDITIONS OF ANY KIND, either express or implied. See the License for the
    15   * specific language governing permissions and limitations under the License.
    16   */
    17  
    18  package connhook
    19  
    20  import (
    21  	"net"
    22  	"sync"
    23  )
    24  
    25  // Conn 包装net.Conn
    26  // 目的:拦截Close操作,用于listener计数的Release以及activeConns的删除
    27  type Conn struct {
    28  	net.Conn
    29  	releaseOnce sync.Once
    30  	closed      bool
    31  	listener    *HookListener
    32  }
    33  
    34  // Close 包装net.Conn.Close, 用于连接计数
    35  func (c *Conn) Close() error {
    36  	if c.closed {
    37  		return nil
    38  	}
    39  
    40  	err := c.Conn.Close()
    41  	c.releaseOnce.Do(func() {
    42  		// 调用监听的listener,释放计数以及activeConns
    43  		// 保证只执行一次
    44  		c.closed = true
    45  
    46  		for i := range c.listener.hooks {
    47  			c.listener.hooks[i].OnRelease(c)
    48  		}
    49  
    50  	})
    51  	return err
    52  }