http包提供了HTTP客户端和服务端的实现

一:http客户端的几种方法

1、 func (c *Client) Get(url string) (resp *Response, err error)
说明: 利用get方法请求指定的url,Get请求指定的页面信息,并返回实体主体

2、func (c *Client) Head(url string) (resp *Response, err error)
说明:利用head方法请求指定的url,Head只返回页面的首部

3、func (c *Client) Post(url string, bodyType string, body io.Reader) (resp *Response, err error)
说明:利用post方法请求指定的URl,如果body也是一个io.Closer,则在请求之后关闭它

4、func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)
说明:利用post方法请求指定的url,利用data的key和value作为请求体.

5、func (c *Client) Do(req *Request) (resp *Response, err error)
说明:Do发送http请求并且返回一个http响应,遵守client的策略,如重定向,cookies以及auth等.当调用者读完resp.body之后应该关闭它,

如果resp.body没有关闭,则Client底层RoundTripper将无法重用存在的TCP连接去服务接下来的请求,如果resp.body非nil,则必须对其进行关闭.
通常来说,经常使用Get,Post,或者PostForm来替代Do

代码示例

1、http.Get

package main

import (
"fmt"
"io/ioutil"
"net/http"
) func main() {
requestUrl := "http://www.baidu.com"
response, err := http.Get(requestUrl) if err != nil {
fmt.Println(err)
} defer response.Body.Close() body, _ := ioutil.ReadAll(response.Body)
fmt.Println(string(body))
}

2、http.Post

package main

import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/url"
) func main() {
requestUrl := "http://www.baidu.com/" // request, err := http.Get(requestUrl)
// request, err := http.Head(requestUrl)
postValue := url.Values{
"username": {"hangmeimei"},
"address": {"anhui"},
"subject": {"world"},
"form": {"beij"},
}
//request, err := http.PostForm(requestUrl, postValue) body := bytes.NewBufferString(postValue.Encode())
request, err := http.Post(requestUrl, "text/html", body)
if err != nil {
fmt.Println(err)
} defer request.Body.Close()
fmt.Println(request.StatusCode)
if request.StatusCode == {
rb, err := ioutil.ReadAll(request.Body)
if err != nil {
fmt.Println(rb)
}
fmt.Println(string(rb))
}
}

3、 http.Do

package main

import (
"fmt"
"io/ioutil"
"net/http"
"strconv"
) func main() {
client := &http.Client{}
request, err := http.NewRequest("GET", "http://www.baidu.com", nil)
if err != nil {
fmt.Println(err)
} cookie := &http.Cookie{Name: "Tom", Value: strconv.Itoa()}
request.AddCookie(cookie) //向request中添加cookie //设置request的header
request.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
request.Header.Set("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3")
request.Header.Set("Accept-Encoding", "gzip,deflate,sdch")
request.Header.Set("Accept-Language", "zh-CN,zh;q=0.8")
request.Header.Set("Cache-Control", "max-age=0")
request.Header.Set("Connection", "keep-alive") response, err := client.Do(request)
if err != nil {
fmt.Println(err)
return
} defer response.Body.Close()
fmt.Println(response.StatusCode)
if response.StatusCode == {
r, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(r))
}
}

二:建立web服务器

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(":8080", nil)
}

说明:
首先调用Http.HandleFunc
往DefaultServeMux的map[string]muxEntry中增加对应的handler和路由规则

http.ListenAndServe
启动一个http服务器,监听8080端口
上面的代码中蕴含着http服务器处理http的流程,有时间可以看源码分析分析

参考:

https://www.cnblogs.com/msnsj/p/4365186.html

http://www.infoq.com/cn/articles/golang-standard-library-part02

最新文章

  1. 安装 Visual Studio Web Tools 的奇怪问题
  2. php 获取远程图片保存到本地
  3. ios程序播放音频文件
  4. You don't have permission to access / on this server
  5. Unity3d 一些 常见路径
  6. mongodb 常见操作转
  7. jstat用法
  8. 三大跨平台网盘--ubuntu one
  9. ARM驱动调试方法、思路总结、笔记
  10. Linux学习(十七)压缩与打包
  11. 关于Serializable的serialVersionUID
  12. linux 7 关闭防火墙 开启sshd服务
  13. 在Linux下,如何分析一个程序达到性能瓶颈的原因
  14. 绘图 Painter转接口封装的方式
  15. Others-阿里专家强琦:流式计算的系统设计和实现
  16. facebook开源项目集合
  17. C语言 函数参数不确定时 需要用到va_start和va_end函数
  18. Codeforces Round #277.5 (Div. 2)部分题解
  19. memached实现tomcat的session共享
  20. 前端开发 - JQuery - 下

热门文章

  1. 常用ASCII码表
  2. "main" java.io.IOException: Mkdirs failed to create /user/centos/hbase-staging (exists=false, cwd=file:/home/centos)
  3. 【Python网络爬虫三】 爬取网页新闻
  4. iOS-修改TableView分割线样式
  5. java笔记1-面向对象思想
  6. python 3 与python 2连接mongoDB的区别
  7. cordova打包遇到Connection timedout:
  8. Qt 5 常用类及基本函数
  9. Nowcoder 练习赛 17 C 操作数 ( k次前缀和、矩阵快速幂打表找规律、组合数 )
  10. TTTTTTTTTTTTTTTTTTT CF 银行转账 图论 智商题