[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 { type Connection struct {
database.Connection database.Connection
config Config
listener net.Listener listener net.Listener
clients map[net.Addr]net.Conn 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() { func init() {
database.RegisterAdapter("socket", Connect) database.RegisterAdapter("socket", Connect)
} }
func Connect(configuration interface{}) (database.Connection, error) { func Connect(configuration interface{}) (database.Connection, error) {
var config Config config := configuration.(map[string]interface{})
config = configuration.(map[string]interface{})
if !config.Enable() { if !config["enable"].(bool) {
return nil, nil return nil, nil
} }
ln, err := net.Listen(config.Type(), config.Address()) ln, err := net.Listen(config["type"].(string), config["address"].(string))
if err != nil { if err != nil {
return nil, err 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) go conn.handleSocketConnection(ln)
log.Println("[socket-database] listen on: ", ln.Addr()) log.Println("[socket-database] listen on: ", ln.Addr())

View File

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