Skip to content

Instantly share code, notes, and snippets.

@timruffles
Created October 14, 2011 14:55
Show Gist options
  • Select an option

  • Save timruffles/1287336 to your computer and use it in GitHub Desktop.

Select an option

Save timruffles/1287336 to your computer and use it in GitHub Desktop.
HTTP server challenge entry
package main
import (
"net"
"regexp"
"fmt"
"bufio"
"bytes"
)
func main() {
get_parser := regexp.MustCompile("[\\?&]value=([^& ]+)*")
sock, _ := net.ListenTCP("tcp",&net.TCPAddr{net.ParseIP("127.0.0.1"),8040})
fmt.Println("Listening")
for {
connection,er := sock.AcceptTCP()
if er == nil {
go handler(connection, get_parser)
}
}
}
func handler(conn net.Conn, re *regexp.Regexp) {
get_match := []byte("GET")
buf := bufio.NewReader(conn)
defer conn.Close()
read := true
for read {
ln, _, er := buf.ReadLine()
read = er == nil
if !bytes.Equal(ln[:3],get_match) {
continue
}
match := re.FindSubmatch([]uint8(ln))
var response, entity []byte
if len(match) > 0 {
response = []byte(fmt.Sprintf("HTTP/1.1 200 OK\r\nContent-length: %v\r\n\r\n",len(match[1])))
entity = match[1]
} else {
response = []byte("HTTP/1.1 400 Bad Request\r\nContent-length: 5\r\n\r\n")
entity = []byte("error")
}
conn.Write(response)
conn.Write(entity)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment