Skip to content

Instantly share code, notes, and snippets.

@elkcityhazard
Last active March 2, 2025 14:19
Show Gist options
  • Save elkcityhazard/62a529813a77acac28c229d3cebfe0d6 to your computer and use it in GitHub Desktop.
Save elkcityhazard/62a529813a77acac28c229d3cebfe0d6 to your computer and use it in GitHub Desktop.
A simple http server using net.Listen
package main
import (
"bufio"
"bytes"
"fmt"
"html/template"
"log"
"net"
"strings"
"github.com/elkcityhazard/fedihire.com/internal/config"
)
var app = config.NewAppConfig()
func main() {
doneChan := make(chan bool)
app.Port = ":8080"
startServer()
<-doneChan
}
func handleConn(c net.Conn) {
path := handleRequest(c)
respondConn(c, path)
defer c.Close()
}
func respondConn(conn net.Conn, path string) {
buf := new(bytes.Buffer)
body := `<!DOCTYPE html><html lang="en"><head><title>Hello World</title></head><body><h1>Hello World</h1>{{with .Path}}<p>Your request path: {{.}}</p>{{end}}</body></html>`
tmpl, err := template.New("hello").Parse(body)
if err != nil {
log.Fatalln(err)
}
type data struct {
Path string
}
d := data{Path: path}
err = tmpl.Execute(buf, d)
if err != nil {
log.Fatalln(err)
}
fmt.Fprint(conn, "HTTP/1.1 200 OK\r\n")
fmt.Fprintf(conn, "Content-Length: %d\r\n", len(buf.Bytes()))
fmt.Fprint(conn, "Content-Type: text/html\r\n")
fmt.Fprint(conn, "\r\n")
buf.WriteTo(conn)
}
func handleRequest(conn net.Conn) string {
i := 0
scanner := bufio.NewScanner(conn)
for scanner.Scan() {
ln := scanner.Text()
if i == 0 {
reqData := strings.Split(ln, " ")
urlPath := reqData[1]
return urlPath
}
fmt.Println(ln)
if ln == "" {
break
}
i++
}
return ""
}
func startServer() {
for {
fmt.Println("starting...")
conn, err := net.Listen("tcp", fmt.Sprintf("%s", app.Port))
if err != nil {
log.Fatalln(err)
}
defer conn.Close()
for {
client, err := conn.Accept()
if err != nil {
log.Fatalln(err)
}
go handleConn(client)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment