当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > Go语言使用HTTP包创建WEB服务器的方法

Go语言使用HTTP包创建WEB服务器的方法

2017年12月08日  | 移动技术网IT编程  | 我要评论

本文实例讲述了go语言使用http包创建web服务器的方法。分享给大家供大家参考,具体如下:

在golang中写一个http web服务器大致是有两种方法:

1 使用net包的net.listen来对端口进行监听

2 使用net/http包

这里是讨论如何使用net/http包创建一个web服务器

net/http请求提供了http客户端和服务端的具体实现

http客户端

先看到的是get,post,postform三个函数。这三个函数直接实现了http客户端

复制代码 代码如下:
import (
    "fmt"
    "net/http"
    "io/ioutil"
)
func main() {
    response,_ := http.get("http://www.baidu.com")
    defer response.body.close()
    body,_ := ioutil.readall(response.body)
    fmt.println(string(body))
}

除了使用这三个函数来建立一个简单客户端,还可以使用:

http.client和http.newrequest来模拟请求

复制代码 代码如下:
package main
import (
    "net/http"
    "io/ioutil"
    "fmt"
)
func main() {
    client := &http.client{}
    reqest, _ := http.newrequest("get", "http://www.baidu.com", nil)
    reqest.header.set("accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
    reqest.header.set("accept-charset","gbk,utf-8;q=0.7,*;q=0.3")
    reqest.header.set("accept-encoding","gzip,deflate,sdch")
    reqest.header.set("accept-language","zh-cn,zh;q=0.8")
    reqest.header.set("cache-control","max-age=0")
    reqest.header.set("connection","keep-alive")
    response,_ := client.do(reqest)
    if response.statuscode == 200 {
        body, _ := ioutil.readall(response.body)
        bodystr := string(body);
        fmt.println(bodystr)
    }
}

如何创建web服务端?

http包封装地非常bt,只需要两行!!:

复制代码 代码如下:
package main
import (
    "net/http"
)
func sayhello(w http.responsewriter, req *http.request) {
    w.write([]byte("hello"))
}
func main() {
    http.handlefunc("/hello", sayhello)
    http.listenandserve(":8001", nil)

}


进行端口的监听:http.listenandserve(":8001", nil)

注册路径处理函数:http.handlefunc("/hello", sayhello)

处理函数:func sayhello(w http.responsewriter, req *http.request)

golang服务器的效率怎样呢?

看看这个帖子:

http://groups.google.com/group/golang-nuts/browse_thread/thread/cde2cc6278cefc90

node.js is 45% faster than golang(确实伤心)

golang服务端的效率确实没有node.js高,几乎是它的一半。但话说回来,如果一些并发量不是很大的site,还是可以使用golang做服务器的。

希望本文所述对大家go语言程序设计有所帮助。

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

相关文章:

验证码:
移动技术网