Created
February 24, 2026 01:38
-
-
Save george124816/eafef9aa54ecca3f95e46ede6b67cd5c to your computer and use it in GitHub Desktop.
http server
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 ( | |
| "fmt" | |
| "log" | |
| "net" | |
| "strings" | |
| ) | |
| type Header struct { | |
| Key string | |
| Value string | |
| } | |
| type Request struct { | |
| Method string | |
| Path string | |
| Version string | |
| Body string | |
| Headers []Header | |
| } | |
| type Response struct { | |
| Version string | |
| StatusCode uint16 | |
| Status string | |
| Body string | |
| } | |
| func (r Response) String() string { | |
| return fmt.Sprintf("%s %d %s\r\n\r\n%s\n", r.Version, r.StatusCode, r.Status, r.Body) | |
| } | |
| func main() { | |
| port := ":4000" | |
| listener, err := net.Listen("tcp", fmt.Sprintf("0.0.0.0%s", port)) | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| defer listener.Close() | |
| log.Printf("listening on port %s", port) | |
| for { | |
| conn, err := listener.Accept() | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| go handleConnection(conn) | |
| } | |
| } | |
| func handleConnection(conn net.Conn) { | |
| defer conn.Close() | |
| data := make([]byte, 1024) | |
| n, err := conn.Read(data) | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| temp := strings.SplitN(string(data[:n]), "\r\n\r\n", 2) | |
| headers := temp[0] | |
| body := temp[1] | |
| statusLine := strings.Split(strings.Split(headers, "\r\n")[0], " ") | |
| secondary_headers := strings.Split(headers, "\r\n")[1:] | |
| var finalHeaders []Header | |
| for _, header := range secondary_headers { | |
| values := strings.Split(header, " ") | |
| header := Header{ | |
| Key: values[0], | |
| Value: values[1], | |
| } | |
| finalHeaders = append(finalHeaders, header) | |
| } | |
| method := statusLine[0] | |
| path := statusLine[1] | |
| version := statusLine[2] | |
| request := Request{ | |
| Method: method, | |
| Path: path, | |
| Version: version, | |
| Headers: finalHeaders, | |
| Body: body, | |
| } | |
| log.Println(request) | |
| response := Response{ | |
| Version: "HTTP/1.0", | |
| StatusCode: uint16(400), | |
| Status: "Bad Request", | |
| Body: "success!", | |
| } | |
| conn.Write([]byte(response.String())) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment