github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/integration/messagebus/glue/handler.go (about) 1 /* 2 * Glue - Robust Go and Javascript Socket Library 3 * Copyright (C) 2015 Roland Singer <roland.singer[at]desertbit.com> 4 * 5 * This program is free software: you can redistribute it and/or modify 6 * it under the terms of the GNU General Public License as published by 7 * the Free Software Foundation, either version 3 of the License, or 8 * (at your option) any later version. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program. If not, see <http://www.gnu.org/licenses/>. 17 */ 18 19 package glue 20 21 import "sync" 22 23 //###############// 24 //### Handler ###// 25 //###############// 26 27 type handler struct { 28 stopChan chan struct{} 29 stopChanClosed bool 30 31 mutex sync.Mutex 32 } 33 34 func newHandler() *handler { 35 return &handler{ 36 stopChanClosed: true, 37 } 38 } 39 40 // New creates a new handler and stopps the previous handler if present. 41 // A stop channel is returned, which is closed as soon as the handler is stopped. 42 func (h *handler) New() chan struct{} { 43 // Lock the mutex. 44 h.mutex.Lock() 45 defer h.mutex.Unlock() 46 47 // Signal the stop request by closing the channel if open. 48 if !h.stopChanClosed { 49 close(h.stopChan) 50 } 51 52 // Create a new stop channel. 53 h.stopChan = make(chan struct{}) 54 55 // Update the flag. 56 h.stopChanClosed = false 57 58 return h.stopChan 59 } 60 61 // Stop the handler if present. 62 func (h *handler) Stop() { 63 // Lock the mutex. 64 h.mutex.Lock() 65 defer h.mutex.Unlock() 66 67 // Signal the stop request by closing the channel if open. 68 if !h.stopChanClosed { 69 close(h.stopChan) 70 h.stopChanClosed = true 71 } 72 }