[BUGFIX] review 1
This commit is contained in:
parent
73219323cf
commit
b20c614a69
@ -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())
|
||||
|
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user