Skip to content

Instantly share code, notes, and snippets.

@taotetek
Created December 8, 2015 13:20
Show Gist options
  • Save taotetek/5d380c0f9abad1f8e021 to your computer and use it in GitHub Desktop.
Save taotetek/5d380c0f9abad1f8e021 to your computer and use it in GitHub Desktop.
why
package main
import (
"bufio"
"encoding/json"
"fmt"
"log"
"net"
"os"
"strings"
"time"
)
const (
ceeToken = "@cee:"
expectedLineParts = 2
retryInterval = 1
)
var (
listenAddress = ":33333"
listenProto = "tcp"
dialAddress = "127.0.0.1:514"
dialProto = "tcp"
oldChar = "."
newChar = "_"
)
func main() {
sendChan := make(chan string)
go func() {
AttemptToConnect:
syslogConn, err := net.Dial(dialProto, dialAddress)
if err != nil {
log.Printf("Error connections to %s:%s", dialProto, dialAddress)
time.Sleep(retryInterval * time.Second)
goto AttemptToConnect
}
defer syslogConn.Close()
for line := range sendChan {
_, err := syslogConn.Write([]byte(line))
if err != nil {
syslogConn.Close()
time.Sleep(retryInterval * time.Second)
goto AttemptToConnect
}
}
}()
l, err := net.Listen(listenProto, listenAddress)
if err != nil {
log.Printf("net.Listen: %s", err)
os.Exit(1)
}
defer l.Close()
for {
conn, err := l.Accept()
if err != nil {
log.Printf("l.Accept: %s", err)
os.Exit(1)
}
defer conn.Close()
go func() {
reader := bufio.NewReader(conn)
for {
line, err := reader.ReadString('\n')
if err != nil {
break
}
lineParts := strings.Split(line, ceeToken)
if len(lineParts) != expectedLineParts {
continue
}
var content map[string]interface{}
err = json.Unmarshal([]byte(lineParts[1]), &content)
if err != nil {
continue
}
newContent := make(map[string]interface{})
for k, v := range content {
k = strings.Replace(k, oldChar, newChar, -1)
newContent[k] = v
}
newJson, err := json.Marshal(newContent)
if err != nil {
continue
}
newLine := fmt.Sprintf("%s%s%s\n",
lineParts[0], ceeToken, string(newJson))
sendChan <- newLine
}
}()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment