golang-http包

基本使用

HTTP客户端,默认使用Http.DefaultClient

1.发送Get请求
resp, err := http.Get("https://jsonplaceholder.typicode.com/posts/1")
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
2.发送post请求,携带json数据
	//模拟json串
	data := map[string]interface{}{
		"name": "kd",
		"age":  18,
	}
	b, _ := json.Marshal(data)
	r:= bytes.NewReader(b)
	
	resp, err := http.Post("http://www.atool.org/httptest.php", "application/json", r)

	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
3.定制客户端与request请求

设定客户端的超时时间为3s

	c := &http.Client{Timeout: time.Second * 3}
	resp, _ := c.Get("http://www.atool.org/httptest.php")

//定制请求:可以通过NewRequest方法实现发送put、delete请求等
	request, err := http.NewRequest("put", "http://www.atool.org/httptest.php", nil)
	if err != nil {
		panic(err)
	}
	resp, err := c.Do(request)

HTTP服务器

ServeMux 是一个 HTTP 请求多路复用器(HTTP Request multiplexer)

1.使用Http.DefaultServeMux
	type CustomeHandle struct {
	}
	
	func (*CustomeHandle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("helloworld"))
	}
	
	//1.使用Handle,需实现ServerHTTP接口
	http.Handle("/", &CustomeHandle{})
	//2.使用Handlefunc,匿名函数
	http.HandleFunc("/a", func(writer http.ResponseWriter, request *http.Request) {
		w.Write([]byte("helloworld"))
	})
	
	http.ListenAndServe(":8080", nil)

2.定制化HTTP服务器

设置读超时、写超时都为1s

	server := http.Server{
		ReadTimeout: time.Second, 
		WriteTimeout: time.Second,
		Addr: "127.0.0.1:8080",
	}
	mux:=http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("hello"))
	})
	
	server.ListenAndServe()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值