Created
October 14, 2011 14:55
-
-
Save timruffles/1287336 to your computer and use it in GitHub Desktop.
HTTP server challenge entry
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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