Skip to content

Instantly share code, notes, and snippets.

@adibfahimi
Created March 19, 2024 10:07
Show Gist options
  • Save adibfahimi/3f77ab92860270f89517357622eaf93d to your computer and use it in GitHub Desktop.
Save adibfahimi/3f77ab92860270f89517357622eaf93d to your computer and use it in GitHub Desktop.
HTTP Server in Golang
package main
import (
"fmt"
"net"
"strings"
)
type HttpRequest struct {
Method string
Path string
Headers map[string]string
Body string
}
type HttpResponse struct {
Headers map[string]string
Status string
Body string
StatusCode int
}
func (r *HttpResponse) String() string {
return fmt.Sprintf("HTTP/1.1 %d %s\n%s\n\n%s", r.StatusCode, r.Status, r.Headers, r.Body)
}
func parseRequest(request string) HttpRequest {
lines := strings.Split(request, "\n")
firstLine := strings.Split(lines[0], " ")
method := strings.TrimSpace(firstLine[0])
path := strings.TrimSpace(firstLine[1])
headers := make(map[string]string)
var i int
for i = 1; i < len(lines); i++ {
line := strings.TrimSpace(lines[i])
if line == "" {
i++
break
}
parts := strings.SplitN(line, ": ", 2)
headers[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])
}
body := strings.Join(lines[i:], "\n")
return HttpRequest{method, path, headers, body}
}
func handleConnection(c net.Conn) {
buf := make([]byte, 1024)
_, err := c.Read(buf)
if err != nil {
fmt.Println("Error reading:", err)
}
request := parseRequest(string(buf))
fmt.Println("Method:", request.Method)
fmt.Println("Path:", request.Path)
fmt.Println("Headers:", request.Headers)
fmt.Println("Body:", request.Body)
response := HttpResponse{
Headers: map[string]string{
"Content-Type": "text/html",
},
Status: "OK",
StatusCode: 200,
Body: "<h1>Hello, World!</h1>",
}
c.Write([]byte(response.String()))
c.Close()
}
func main() {
conn, err := net.Listen("tcp", "127.0.0.1:3000")
if err != nil {
fmt.Println("Error listening:", err)
}
defer conn.Close()
fmt.Println("Server listening on 127.0.0.1:3000")
for {
c, err := conn.Accept()
if err != nil {
fmt.Println("Error accepting connection:", err)
}
go handleConnection(c)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment