kunt

golang IRC bot
git clone git@git.2f30.org/kunt.git
Log | Files | Refs | LICENSE

events.go (936B)


      1 // Copyright 2013 TLH and dsp. All rights reserved.
      2 // Use of this source code is governed by a BSD-style
      3 // license that can be found in the LICENSE file.
      4 
      5 package irc
      6 
      7 import (
      8 	"fmt"
      9 )
     10 
     11 type Event struct {
     12 	Command string
     13 	Fn      func(Message)
     14 }
     15 
     16 func (i *Context) AddEventHandler(ev Event) error {
     17 	i.Lock()
     18 	defer i.Unlock()
     19 	for j := 0; j < i.evnum; j++ {
     20 		if i.ev[j].Command == ev.Command {
     21 			return fmt.Errorf("Event %s already handled",
     22 				ev.Command)
     23 		}
     24 	}
     25 	i.ev = append(i.ev, ev)
     26 	i.evnum++
     27 	return nil
     28 }
     29 
     30 func (i *Context) DelEventHandler(ev *Event) error {
     31 	i.Lock()
     32 	defer i.Unlock()
     33 	for j := 0; j < i.evnum; j++ {
     34 		if &i.ev[j] == ev {
     35 			i.ev = append(i.ev[:j], i.ev[j+1:]...)
     36 			return nil
     37 		}
     38 	}
     39 	return fmt.Errorf("Event handler not found")
     40 }
     41 
     42 func (i *Context) dispatchHandler(msg Message) {
     43 	i.Lock()
     44 	defer i.Unlock()
     45 	for _, v := range i.ev {
     46 		if v.Command == msg.Command {
     47 			v.Fn(msg)
     48 			break
     49 		}
     50 	}
     51 }