go語(yǔ)言實(shí)現(xiàn)http服務(wù)端與客戶(hù)端的例子

go語(yǔ)言的net/http包的使用非常的簡(jiǎn)單優(yōu)雅

成都創(chuàng)新互聯(lián)公司主要從事網(wǎng)站設(shè)計(jì)制作、成都網(wǎng)站設(shè)計(jì)、網(wǎng)頁(yè)設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)桐柏,十多年網(wǎng)站建設(shè)經(jīng)驗(yàn),價(jià)格優(yōu)惠、服務(wù)專(zhuān)業(yè),歡迎來(lái)電咨詢(xún)建站服務(wù):028-86922220

(1)服務(wù)端

package main
 
import (
 "flag"
 "fmt"
 "net/http"
)
 
func main() {
 host := flag.String("host", "127.0.0.1", "listen host")
 port := flag.String("port", "80", "listen port")
 
 http.HandleFunc("/hello", Hello)
 
 err := http.ListenAndServe(*host+":"+*port, nil)
 
 if err != nil {
 panic(err)
 }
}
 
func Hello(w http.ResponseWriter, req *http.Request) {
<p> w.Write([]byte("Hello World"))</p>}

http.HandleFunc用來(lái)注冊(cè)路徑處理函數(shù),會(huì)根據(jù)給定路徑的不同,調(diào)用不同的函數(shù)

http.ListenAndSercer監(jiān)聽(tīng)iP與端口,本機(jī)IP可以省略不寫(xiě),僅書(shū)寫(xiě)冒號(hào)加端口,如http.ListenAndSercer(“:8080”, nil)

路徑處理函數(shù),參數(shù)必須為w http.ResponseWriter和 req *http.Request且不能有返回值

測(cè)試結(jié)果:成功

(2)客戶(hù)端

package main
 
import (
 "fmt"
 "io/ioutil"
 "net/http"
)
 
func main() {
 response, _ := http.Get("http://localhost:80/hello")
 defer response.Body.Close()
 body, _ := ioutil.ReadAll(response.Body)
 fmt.Println(string(body))
}

測(cè)試結(jié)果:成功!

go語(yǔ)言實(shí)現(xiàn)http服務(wù)端與客戶(hù)端的例子

以上這篇go語(yǔ)言實(shí)現(xiàn)http服務(wù)端與客戶(hù)端的例子就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持創(chuàng)新互聯(lián)。

本文標(biāo)題:go語(yǔ)言實(shí)現(xiàn)http服務(wù)端與客戶(hù)端的例子
分享網(wǎng)址:http://www.muchs.cn/article4/phohie.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供移動(dòng)網(wǎng)站建設(shè)、全網(wǎng)營(yíng)銷(xiāo)推廣網(wǎng)站排名、網(wǎng)站設(shè)計(jì)公司、網(wǎng)站設(shè)計(jì)、營(yíng)銷(xiāo)型網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)