Skip to content

Commit

Permalink
Added golang http client and server on net/http lib
Browse files Browse the repository at this point in the history
  • Loading branch information
k8s4 committed Oct 24, 2024
1 parent 48a2ab6 commit a337626
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 1 deletion.
53 changes: 53 additions & 0 deletions examples/golang/cource/06e_network/clients/http.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package client

import (
"fmt"
"net/http"
"bufio"
)

func HTTPClientGet() {
resp, err := http.Get("http://localhost:8080")
if err != nil {
panic(err)
}
defer resp.Body.Close()

fmt.Println("Response status:", resp.Status)

scanner := bufio.NewScanner(resp.Body)
for i := 0; scanner.Scan() && i < 5; i++ {
fmt.Println(scanner.Text())
}

if err := scanner.Err(); err != nil {
panic(err)
}
}

func HTTPClientHeaderGet() {
client := &http.Client{}
req, _ := http.NewRequest("GET", "http://localhost:8080/headers", nil)
req.Header.Add("test", "test")
resp, err := client.Do(req)

if err != nil {
panic(err)
}
defer resp.Body.Close()
for name, headers := range resp.Header {
for _, h := range headers {
fmt.Printf("Header: %v: %v\n", name, h)
}
}
fmt.Println("Response status:", resp.Status)

scanner := bufio.NewScanner(resp.Body)
for i := 0; scanner.Scan() && i < 5; i++ {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
panic(err)
}

}
5 changes: 4 additions & 1 deletion examples/golang/cource/06e_network/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ func main() {
fmt.Println("Started test servers.")
// server.TCPServer()
// server.UDPServer()
// server.HTTPServer()
// client.TCPClient()
client.UDPClient()
// client.UDPClient()
client.HTTPClientGet()
client.HTTPClientHeaderGet()
}
28 changes: 28 additions & 0 deletions examples/golang/cource/06e_network/servers/http.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package server

import (
"fmt"
"net/http"
)

func some(writer http.ResponseWriter, req *http.Request) {
fmt.Fprintf(writer, "Something in the water!\n")
}

func headers(writer http.ResponseWriter, req *http.Request) {
for name, headers := range req.Header {
for _, h := range headers {
fmt.Fprintf(writer, "%v: %v\n", name, h)
}
}
}

func HTTPServer() {
http.HandleFunc("/some", some)
http.HandleFunc("/headers", headers)

err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Println(err)
}
}

0 comments on commit a337626

Please sign in to comment.