Skip to content

Instantly share code, notes, and snippets.

@mcroydon
Created January 12, 2012 00:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcroydon/1597581 to your computer and use it in GitHub Desktop.
Save mcroydon/1597581 to your computer and use it in GitHub Desktop.
Performance-oriented silly text-based protocol server in go.
package main
import (
"bufio"
"flag"
"fmt"
"io"
"log"
"net"
"net/textproto"
"runtime"
)
// Flags used to modify default behavior.
var (
address = flag.String("a", "0.0.0.0", "the IP address to listen on.")
port = flag.Int("p", 31337, "the port to listen on.")
maxprocs = flag.Int("n", 1, "the number of CPUs to use simultaneously.")
)
// The main function listens for connections and dispatches them to handleClient via a goroutine.
func main() {
// Parse flags and set GOMAXPROCS.
flag.Parse()
runtime.GOMAXPROCS(*maxprocs)
// Create a listener on the specified address:port.
listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", *address, *port))
if err != nil {
log.Fatal(err)
}
log.Printf("Serving silly protocols on %s:%d", *address, *port)
// Dispatch each incoming request.
for {
conn, err := listener.Accept()
defer conn.Close()
if err != nil {
log.Println(err)
}
go handleClient(conn, conn)
}
}
// Handle a connection, respond as needed, return when the connection closes.
func handleClient(in io.Reader, out io.Writer) {
// Set up readers and writers.
reader := bufio.NewReader(in)
writer := bufio.NewWriter(out)
textreader := textproto.NewReader(reader)
textwriter := textproto.NewWriter(writer)
for {
// Handle a line.
line, err := textreader.ReadLine()
// Handle possible errors.
switch err {
default:
// Log the error.
log.Println(err)
case nil:
// Do nothing.
case io.EOF:
// Connection closed on the other end so we return.
return
}
log.Println(line)
// Handle the incoming line based on several silly text protocol requests and responses.
// If we don't understand the request, the proper response is DUNNO\r\n
switch line {
default:
textwriter.PrintfLine("DUNNO")
case "ORLY":
textwriter.PrintfLine("YA RLY")
case "HERP":
textwriter.PrintfLine("DERP")
case "NOWAI":
textwriter.PrintfLine("YESWAI")
case "OHAI":
textwriter.PrintfLine("OHAI")
case "NOM":
textwriter.PrintfLine("NOM NOM NOM")
case "OMG":
textwriter.PrintfLine("WTF")
case "WTF":
textwriter.PrintfLine("BBQ")
case "OMGWTFBBQ":
textwriter.PrintfLine("LOLLERSKATES")
}
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment