我是靠谱客的博主 心灵美苗条,这篇文章主要介绍go语言实现http服务端与客户端的例子,现在分享给大家,希望可以做个参考。

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

(1)服务端

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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)客户端

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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)) }

测试结果:成功!

以上这篇go语言实现http服务端与客户端的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持靠谱客。

最后

以上就是心灵美苗条最近收集整理的关于go语言实现http服务端与客户端的例子的全部内容,更多相关go语言实现http服务端与客户端内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(145)

评论列表共有 0 条评论

立即
投稿
返回
顶部