[BUGFIX] review 1

This commit is contained in:
Martin Geno 2017-04-27 22:28:31 +02:00
parent 73219323cf
commit b20c614a69
No known key found for this signature in database
GPG Key ID: F0D39A37E925E941
2 changed files with 10 additions and 20 deletions

View File

@ -16,39 +16,26 @@ import (
type Connection struct {
database.Connection
config Config
listener net.Listener
clients map[net.Addr]net.Conn
}
type Config map[string]interface{}
func (c Config) Enable() bool {
return c["enable"].(bool)
}
func (c Config) Type() string {
return c["type"].(string)
}
func (c Config) Address() string {
return c["address"].(string)
}
func init() {
database.RegisterAdapter("socket", Connect)
}
func Connect(configuration interface{}) (database.Connection, error) {
var config Config
config = configuration.(map[string]interface{})
if !config.Enable() {
config := configuration.(map[string]interface{})
if !config["enable"].(bool) {
return nil, nil
}
ln, err := net.Listen(config.Type(), config.Address())
ln, err := net.Listen(config["type"].(string), config["address"].(string))
if err != nil {
return nil, err
}
conn := &Connection{config: config, listener: ln, clients: make(map[net.Addr]net.Conn)}
conn := &Connection{listener: ln, clients: make(map[net.Addr]net.Conn)}
go conn.handleSocketConnection(ln)
log.Println("[socket-database] listen on: ", ln.Addr())

View File

@ -2,6 +2,7 @@ package socket
import (
"encoding/json"
"log"
"net"
)
@ -14,6 +15,7 @@ func (config *Connection) handleSocketConnection(ln net.Listener) {
for {
c, err := ln.Accept()
if err != nil {
log.Println("[socket-database] error during connection of a client", err)
continue
}
config.clients[c.RemoteAddr()] = c
@ -21,13 +23,14 @@ func (config *Connection) handleSocketConnection(ln net.Listener) {
}
func (conn *Connection) sendJSON(msg EventMessage) {
for i, c := range conn.clients {
for addr, c := range conn.clients {
d := json.NewEncoder(c)
err := d.Encode(&msg)
if err != nil {
log.Println("[socket-database] client has not recieve event:", err)
c.Close()
delete(conn.clients, i)
delete(conn.clients, addr)
}
}
}