Created
February 1, 2025 03:45
-
-
Save Zhomart/6dc08d7b0ea2713056086bad976a08ac to your computer and use it in GitHub Desktop.
v1
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" | |
"io" | |
"log" | |
"net" | |
"os" | |
"strings" | |
) | |
func main() { | |
arguments := os.Args | |
if len(arguments) == 1 { | |
fmt.Println("Provide a port") | |
return | |
} | |
PORT := fmt.Sprintf(":%v", arguments[1]) | |
server, err := net.Listen("tcp4", PORT) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer server.Close() | |
for { | |
fmt.Println("Litening...") | |
client, err := server.Accept() | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
go handleConnection(client) | |
} | |
} | |
// Hardware: wifi adapter | |
// Driver: reads data from wifi | |
// OS: has cache 1kb | |
// func readAll() []byte { | |
// fullData := make([]byte, 8*1024*1024) | |
// } | |
type Request struct { | |
Method string | |
Path string | |
Header map[string]string | |
} | |
func parseRequest(data []byte) Request { | |
// | |
} | |
func handleConnection(client net.Conn) { | |
fmt.Printf("Serving: %v\n", client.RemoteAddr().String()) | |
tmp := make([]byte, 8*1024*1024) | |
defer client.Close() | |
n, err := client.Read(tmp) | |
if err != nil { | |
if err != io.EOF { | |
fmt.Println("read error") | |
} | |
return | |
} | |
fmt.Printf("size = %d", n) | |
fmt.Println("--- begin ----") | |
fmt.Println(string(tmp)) | |
fmt.Println("--- end ----") | |
chunks := strings.Split(string(tmp), " ") | |
if len(chunks) < 3 { | |
fmt.Println("Invalid request line") | |
return | |
} | |
method := chunks[0] | |
path := chunks[1] | |
httpVersion := chunks[2] | |
fmt.Println("http method = " + method) | |
fmt.Println("http path = " + path) | |
fmt.Println("http version = " + httpVersion) | |
var response string | |
if path == "/" { | |
response = "HTTP/1.1 200 OK\n" + "Content-Type: text/html;\n\n" | |
response += handleHomePath() | |
} else if path == "/upload" && method == "POST" { | |
handleUpload() | |
} | |
client.Write([]byte(response)) | |
} | |
func handleHomePath() string { | |
data, err := os.ReadFile("public/index.html") | |
if err == nil { | |
return string(data) | |
} else { | |
fmt.Println(err) | |
return "error reading file" | |
} | |
} | |
func handleUpload() { | |
fmt.Println("handleUpload") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment