github.com/cloudwego/kitex@v0.9.0/server/hooks.go (about)

     1  /*
     2   * Copyright 2021 CloudWeGo Authors
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *  http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package server
    18  
    19  import "sync"
    20  
    21  // RegisterStartHook add hook which is executed after the server starts.
    22  func RegisterStartHook(h func()) {
    23  	muStartHooks.Lock()
    24  	defer muStartHooks.Unlock()
    25  	onServerStart.add(h)
    26  }
    27  
    28  // RegisterShutdownHook add hook which is executed after the server shutdown.
    29  func RegisterShutdownHook(h func()) {
    30  	muShutdownHooks.Lock()
    31  	defer muShutdownHooks.Unlock()
    32  	onShutdown.add(h)
    33  }
    34  
    35  // Hooks is a collection of func.
    36  type Hooks []func()
    37  
    38  // Add adds a hook.
    39  func (h *Hooks) add(g func()) {
    40  	*h = append(*h, g)
    41  }
    42  
    43  // Server hooks
    44  var (
    45  	onServerStart   Hooks      // Hooks executes after the server starts.
    46  	muStartHooks    sync.Mutex // onServerStart 's mutex
    47  	onShutdown      Hooks      // Hooks executes when the server is shutdown gracefully.
    48  	muShutdownHooks sync.Mutex // onShutdown 's mutex
    49  )