Go语言使用HTTP包创建WEB服务器的方法
2016-07-27 16:01
976 查看
在Golang中写一个http web服务器大致是有两种方法:
1 使用net包的net.Listen来对端口进行监听
2 使用net/http包
这里是讨论如何使用net/http包创建一个web服务器
net/http请求提供了HTTP客户端和服务端的具体实现
http客户端
先看到的是Get,Post,PostForm三个函数。这三个函数直接实现了http客户端
"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来模拟请求
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 mainimport (
"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语言程序设计有所帮助。
您可能感兴趣的文章:
相关文章推荐
- RPC failed; result=22, HTTP code = 411
- HTTP Header 属性列表
- nginx中http核心模块的配置指令2
- nginx中http核心模块的配置指令3
- nginx中http核心模块的配置指令4
- nginx中http的fastcgi模块的配置指令1
- 如何在 Linux 中快速地通过 HTTP 提供文件访问服务
- 深入HTTP head的使用详解
- Ruby程序中发送基于HTTP协议的请求的简单示例
- ASP 中使用 HTTP 协议发送参数详解
- C#基于socket模拟http请求的方法
- http www安全必备知识
- asp HTTP 500错误 常见问题分析
- http代理相关知识分析
- 在Node.js中使用HTTP上传文件的方法
- php错误提示failed to open stream: HTTP request failed!的完美解决方法
- php提示Failed to write session data错误的解决方法