go,package main,,import (, "fmt", "net/http",),,func main() {, http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {, fmt.Fprintf(w, "Hello, 你好!"), }),, http.ListenAndServe(":8080", nil),},
`,,客戶端代碼:,
`go,package main,,import (, "io/ioutil", "net/http",),,func main() {, resp, err := http.Get("http://localhost:8080"), if err != nil {, panic(err), }, defer resp.Body.Close(),, body, err := ioutil.ReadAll(resp.Body), if err != nil {, panic(err), },, fmt.Println("Server response:", string(body)),},
`,,在上述示例中,服務器端使用
http.HandleFunc注冊處理函數(shù),并監(jiān)聽8080端口??蛻舳送ㄟ^
http.Get`發(fā)送HTTP請求,并讀取響應內(nèi)容。
在Go語言中,實現(xiàn)HTTP服務器和客戶端可以通過使用net/http包來實現(xiàn),下面我將詳細地介紹如何創(chuàng)建一個簡單的HTTP服務器和HTTP客戶端。
創(chuàng)建HTTP服務器
1、導入"net/http"包
2、使用http.HandleFunc()函數(shù)注冊處理函數(shù)
3、使用http.ListenAndServe()啟動服務器
以下是創(chuàng)建HTTP服務器的示例代碼:
package main import ( "fmt" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, you've requested: %s ", r.URL.Path) }) http.ListenAndServe(":8080", nil) }
創(chuàng)建HTTP客戶端
1、使用http.Get()發(fā)送GET請求
2、使用resp.Body讀取響應體
3、關閉resp.Body以釋放資源
以下是創(chuàng)建HTTP客戶端的示例代碼:
package main import ( "io/ioutil" "net/http" ) func main() { resp, err := http.Get("http://localhost:8080/") if err != nil { panic(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err) } fmt.Println("Server response:", string(body)) }
相關問題與解答
問題1:如何在HTTP服務器中處理POST請求?
答:在HTTP服務器中處理POST請求,可以使用http.Post()或http.PostForm()函數(shù),并在處理函數(shù)中通過r.ParseForm()解析表單數(shù)據(jù),示例如下:
http.HandleFunc("/post", func(w http.ResponseWriter, r *http.Request) { r.ParseForm() fmt.Fprintf(w, "You've posted: %s ", r.FormValue("key")) })
問題2:如何在HTTP客戶端中發(fā)送POST請求?
答:在HTTP客戶端中發(fā)送POST請求,可以使用http.NewRequest()創(chuàng)建請求,并設置請求方法為POST,然后使用http.Client發(fā)送請求,示例如下:
client := &http.Client{}
req, err := http.NewRequest("POST", "http://localhost:8080/post", strings.NewReader(key=value
))
if err != nil {
panic(err)
}
req.Header.Set("ContentType", "application/xwwwformurlencoded")
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Println("Server response:", string(body))