Created
November 30, 2019 22:17
-
-
Save dhermes/2de29387438a3ac46b31832bebc70cb7 to your computer and use it in GitHub Desktop.
Basic HTTP server over TCP. Prints entire TCP body as string for each request handled.
This file contains 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 ( | |
"fmt" | |
"log" | |
"net" | |
) | |
const ( | |
chunkSize = 4096 | |
) | |
func handle(conn net.Conn) { | |
defer conn.Close() | |
request(conn) | |
} | |
func request(conn net.Conn) { | |
started := false | |
var tcpBody []byte | |
part := make([]byte, chunkSize) | |
bytesRead, _ := conn.Read(part) | |
for bytesRead > 0 { | |
tcpBody = append(tcpBody, part[:bytesRead]...) | |
if !started { | |
index(conn) | |
} | |
bytesRead, _ = conn.Read(part) | |
started = true | |
} | |
fmt.Printf("Serving on %q to client at %q\n%q\n", conn.LocalAddr(), conn.RemoteAddr(), tcpBody) | |
} | |
func index(conn net.Conn) { | |
body := "<html><body>Hello World</body></html>" | |
fmt.Fprint(conn, "HTTP/1.1 200 OK\r\n") | |
fmt.Fprintf(conn, "Content-Length: %d\r\n", len(body)) | |
fmt.Fprint(conn, "Content-Type: text/html\r\n") | |
fmt.Fprint(conn, "Connection: close\r\n") | |
fmt.Fprint(conn, "\r\n") | |
fmt.Fprint(conn, body) | |
} | |
func main() { | |
// H/T: https://github.com/GoesToEleven/golang-web-dev/tree/2bdef48e8e7bf310300130555e89435349f64197/016_building-a-tcp-server-for-http | |
li, err := net.Listen("tcp", ":5007") | |
if err != nil { | |
log.Fatalln(err.Error()) | |
} | |
defer li.Close() | |
for { | |
conn, err := li.Accept() | |
if err != nil { | |
log.Println(err.Error()) | |
continue | |
} | |
go handle(conn) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment