学习需要耐心&&时间,更重要的是你要学会坚持!
当前位置:首页 > Go语言 > 正文

go语言 实现 http服务端与客户端 通讯

2022-03-15 Go语言 Go语言圈


go语言的net/http包的使用非常的简单优雅

1)服务端

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用来注册路径处理函数,会根据给定路径的不同,调用不同的函数
http.ListenAndSercer监听iP与端口,本机IP可以省略不写,仅书写冒号加端口,如http.ListenAndSercer(“:8080”, nil)

路径处理函数,参数必须为w http.ResponseWriter和 req *http.Request且不能有返回值
测试结果:成功

2)客户端
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))
}
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))
}

测试结果:成功!
图片
 

以上是本文的全部内容,希望对大家学习有帮助,也希望大家多多支持 磊丰的技术博客 感谢阅读!

站长磊丰学长
男,文化程度不高,性格有点犯二,爱好学习与分享,闲着没事喜欢研究各种代码,写写文章,潜水技术宅。
关注公众号:PHP自学中心
关注公众号:Go语言学习圈
学习与交流:程序员技术微信群

标签

网站工具箱