From 0e679e17980c566e2daf81eab6ee06d94969f8e2 Mon Sep 17 00:00:00 2001 From: Ian Kent Date: Wed, 16 Apr 2014 23:29:23 +0100 Subject: [PATCH] Basic go echo server --- mailhog/smtp.go | 8 ++++++ main.go | 67 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 mailhog/smtp.go create mode 100644 main.go diff --git a/mailhog/smtp.go b/mailhog/smtp.go new file mode 100644 index 0000000..c58b1b9 --- /dev/null +++ b/mailhog/smtp.go @@ -0,0 +1,8 @@ +package mailhog + +type Message struct { + From string + To string + Data []byte + Helo string +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..df70353 --- /dev/null +++ b/main.go @@ -0,0 +1,67 @@ +package main + +import ( + "flag" + "log" + "net" +) + +var conf = map[string]string { + "BIND_ADDRESS": "0.0.0.0:1025", +} + +func config() { + var listen string + + flag.StringVar(&listen, "listen", "0.0.0.0:1025", "Bind interface and port, e.g. 0.0.0.0:1025 or just :1025") + flag.Parse() + + conf["BIND_ADDRESS"] = listen +} + +func main() { + config() + + ln := listen(conf["BIND_ADDRESS"]) + defer ln.Close() + + for { + conn, err := ln.Accept() + if err != nil { + log.Printf("Error accepting connection: %s\n", err) + continue + } + defer conn.Close() + + go accept(conn) + } +} + +func listen(bind string) (*net.TCPListener) { + log.Printf("Binding to address: %s\n", bind) + ln, err := net.Listen("tcp", bind) + if err != nil { + log.Fatalf("Error listening on socket: %s\n", err) + } + return ln.(*net.TCPListener) +} + +func accept(conn net.Conn) { + buf := make([]byte, 1024) + n, err := conn.Read(buf) + + if err != nil { + log.Printf("Error reading from socket: %s", err) + return + } + + log.Printf("Received %s bytes: %s\n", n, string(buf)) + + _, err = conn.Write(buf) + if err != nil { + log.Printf("Error writing to socket: %s\n", err) + return + } + + log.Printf("Reply sent\n") +}