Created
October 28, 2023 13:57
-
-
Save twentyse7en/cd0bf90f154a60d6056c127d572bc269 to your computer and use it in GitHub Desktop.
HTTP server in go
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" | |
"net" | |
"io/ioutil" | |
) | |
// optional to view the structure of request | |
func exploreRequest(conn net.Conn) { | |
// I assume | |
// as the connection isn't closed | |
// it will wait to read more bytes | |
// so it will be blocking | |
// server won't receive anything | |
resp, err := ioutil.ReadAll(conn); | |
if err != nil { | |
fmt.Println("error while reading") | |
} | |
fmt.Println("Data from URL:", string(resp)) | |
} | |
func handleRequest(conn net.Conn) { | |
defer conn.Close() | |
// parse incoming request | |
// exploreRequest(conn) | |
// send a response | |
response := "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello, world!" | |
conn.Write([]byte(response)) | |
} | |
func main() { | |
listener, err := net.Listen("tcp", ":8080") | |
if err != nil { | |
fmt.Println("Error starting server", err) | |
return | |
} | |
// free resourse when function returns | |
defer listener.Close() | |
// server is ok to start | |
fmt.Println("server is listening on port 8080") | |
// we need a infinite loop, which will serve the request | |
for { | |
// blocks the loop untill a request is made | |
conn, err := listener.Accept(); | |
fmt.Println("conn is accepted") | |
if err != nil { | |
fmt.Println("Error accepting connection:", err) | |
continue | |
} | |
// handle the request | |
// it shouldn't block the next request | |
// so running in seperate thread | |
// this is go routine | |
go handleRequest(conn) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment