Merge pull request #113 from iopred/develop

Clean up mutexes around s.handlers so they exist only in discord.go
This commit is contained in:
Bruce 2016-02-18 21:48:31 -06:00
commit 296a118712
2 changed files with 11 additions and 18 deletions

View file

@ -125,8 +125,7 @@ func New(args ...interface{}) (s *Session, err error) {
// AddHandler allows you to add an event handler that will be fired anytime // AddHandler allows you to add an event handler that will be fired anytime
// the given event is triggered. // the given event is triggered.
func (s *Session) AddHandler(handler interface{}) { func (s *Session) AddHandler(handler interface{}) {
s.Lock() s.initialize()
defer s.Unlock()
handlerType := reflect.TypeOf(handler) handlerType := reflect.TypeOf(handler)
@ -138,11 +137,8 @@ func (s *Session) AddHandler(handler interface{}) {
panic("Unable to add event handler, first argument must be of type *discordgo.Session.") panic("Unable to add event handler, first argument must be of type *discordgo.Session.")
} }
if s.handlers == nil {
s.Unlock()
s.initialize()
s.Lock() s.Lock()
} defer s.Unlock()
eventType := handlerType.In(1) eventType := handlerType.In(1)
@ -155,12 +151,12 @@ func (s *Session) AddHandler(handler interface{}) {
if handlers == nil { if handlers == nil {
handlers = []reflect.Value{} handlers = []reflect.Value{}
} }
s.handlers[eventType] = append(handlers, reflect.ValueOf(handler))
handlers = append(handlers, reflect.ValueOf(handler))
s.handlers[eventType] = handlers
} }
func (s *Session) handle(event interface{}) { func (s *Session) handle(event interface{}) {
s.initialize()
s.RLock() s.RLock()
defer s.RUnlock() defer s.RUnlock()
@ -182,6 +178,11 @@ func (s *Session) handle(event interface{}) {
// initialize adds all internal handlers and state tracking handlers. // initialize adds all internal handlers and state tracking handlers.
func (s *Session) initialize() { func (s *Session) initialize() {
s.Lock() s.Lock()
if s.handlers != nil {
s.Unlock()
return
}
s.handlers = map[interface{}][]reflect.Value{} s.handlers = map[interface{}][]reflect.Value{}
s.Unlock() s.Unlock()

View file

@ -284,14 +284,6 @@ var eventToInterface = map[string]interface{}{
// Events will be handled by any implemented handler in Session. // Events will be handled by any implemented handler in Session.
// All unhandled events will then be handled by OnEvent. // All unhandled events will then be handled by OnEvent.
func (s *Session) event(messageType int, message []byte) { func (s *Session) event(messageType int, message []byte) {
s.RLock()
if s.handlers == nil {
s.RUnlock()
s.initialize()
} else {
s.RUnlock()
}
var err error var err error
var reader io.Reader var reader io.Reader
reader = bytes.NewBuffer(message) reader = bytes.NewBuffer(message)