当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > go语言实现http服务端与客户端的例子

go语言实现http服务端与客户端的例子

2019年09月09日  | 移动技术网IT编程  | 我要评论

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))
}

测试结果:成功!

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网