Go语言_HTTP包

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

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

2 使用net/http包

 

http客户端

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

net/http请求提供了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)
    }
}

clip_image001

如何创建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)



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值