First commit

This commit is contained in:
Hamcha 2016-02-08 13:47:10 +00:00
commit 8b9084ec06
6 changed files with 130 additions and 0 deletions

4
Makefile Normal file
View File

@ -0,0 +1,4 @@
all: broker
broker:
go build -o clessy-broker ./broker

9
broker/action.go Normal file
View File

@ -0,0 +1,9 @@
package broker
import (
"../tg"
)
func executeClientCommand(action tg.ClientCommand) {
}

67
broker/clients.go Normal file
View File

@ -0,0 +1,67 @@
package main
import (
"bufio"
"encoding/json"
"fmt"
"log"
"net"
"../tg"
)
var clients []net.Conn
func startClientsServer(bind string) {
listener, err := net.Listen("tcp", bind)
assert(err)
// Accept loop
for {
c, err := listener.Accept()
if err != nil {
log.Printf("Can't accept client: %s\n", err.Error())
continue
}
clients = append(clients, c)
go handleClient(c)
}
}
func handleClient(c net.Conn) {
b := bufio.NewReader(c)
defer c.Close()
// Start reading messages
for {
bytes, _, err := b.ReadLine()
if err != nil {
break
}
var cmd tg.ClientCommand
err = json.Unmarshal(bytes, &cmd)
if err != nil {
log.Printf("Can't parse JSON: %s\r\n", err.Error())
continue
}
executeClientCommand(cmd)
}
removeCon(c)
}
func removeCon(c net.Conn) {
for i, con := range Clients {
if c == con {
clients = append(clients[:i], clients[i+1:]...)
}
}
}
func broadcast(message string) {
for _, c := range clients {
_, err := fmt.Fprintf(c, message+"\r\n")
if err != nil {
removeCon(c)
}
}
}

43
broker/main.go Normal file
View File

@ -0,0 +1,43 @@
package main
import (
"encoding/json"
"flag"
"net/http"
"os"
)
type Config struct {
BindServer string /* Address:Port to bind for Telegram */
BindClients string /* Address:Port to bind for clients */
Token string /* Telegram bot token */
WebhookURL string /* Webhook URL */
}
func assert(err error) {
if err != nil {
panic(err)
}
}
func main() {
cfgpath := flag.String("config", "config.json", "Path to configuration file")
flag.Parse()
file, err := os.Open(*cfgpath)
assert(err)
var config Config
err = json.NewDecoder(file).Decode(&config)
assert(err)
// Setup webhook handler
go func() {
http.HandlerFunc(config.Token, webhook)
err := http.ListenAndServe(config.BindServer, nil)
assert(err)
}()
// Create server for clients
startClientsServer(config.BindClients)
}

3
config.json.sample Normal file
View File

@ -0,0 +1,3 @@
{
}

4
tg/command.go Normal file
View File

@ -0,0 +1,4 @@
package tg
type ClientCommand struct {
}