sever端
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello, HTTP Server!")
})
port := 8080
serverAddr := fmt.Sprintf(":%d", port)
fmt.Printf("HTTP server listening on http://localhost:%d\n", port)
err := http.ListenAndServe(serverAddr, nil)
if err != nil {
fmt.Println("Error starting HTTP server:", err)
}
}
client端
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
url := "http://localhost:8080"
// 发送 GET 请求
resp, err := http.Get(url)
if err != nil {
fmt.Println("Error sending GET request:", err)
return
}
defer resp.Body.Close()
// 读取服务器的响应
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading response:", err)
return
}
fmt.Printf("Received response from server: %s\n", string(body))
}
�
�