zoukankan      html  css  js  c++  java
  • Google资深工程师深度讲解Go语言http及其他标准库(十一)

    一.HTTP标准库

    • 使用http客户端发送请求
    • 使用http.client控制请求头部等
    • 使用httputil简化工作
    package main
    
    import (
    	"fmt"
    	"net/http"
    	"net/http/httputil"
    )
    
    func main() {
    	resp,err:=http.Get("http://www.imooc.com")
    	if err!=nil {
    		panic(err)
    	}
    	defer resp.Body.Close()
    	s,err:=httputil.DumpResponse(resp,true)
    	if err !=nil{
    		panic(err)
    	}
    	fmt.Printf("%s\n",s)
    }
    

    升级版

    package main
    
    import (
    	"fmt"
    	"net/http"
    	"net/http/httputil"
    )
    
    func main() {
    	request,err:=http.NewRequest(http.MethodGet,"http://www.imooc.com",nil)
    	request.Header.Add("User-Agent"," Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1")
    
    	client:=http.Client{
    		Transport:     nil,//设置代理服务器
    		CheckRedirect: func( //重定向从这里过
    			req *http.Request,
    			via []*http.Request) error {
    				fmt.Println("redirect:",req)
    			return nil
    		},
    		Jar:           nil,//模拟登陆,设置cookie
    		Timeout:       0,
    	}
    	resp,err:=client.Do(request)
    	//resp,err:=http.DefaultClient.Do(request)
    	//resp,err:=http.Get("http://www.imooc.com")
    	if err!=nil {
    		panic(err)
    	}
    	defer resp.Body.Close()
    	s,err:=httputil.DumpResponse(resp,true)
    	if err !=nil{
    		panic(err)
    	}
    	fmt.Printf("%s\n",len(s))
    }
    

    二.http服务器的性能分析

    • import _"net/http/pprof"
    • 访问/debug/pprof
    • 使用 go tool pprof分析性能
    import (
    	"./filelisting"
    	"log"
    	"net/http"
    	"os"
    	_ "net/http/pprof"  //库前加下划线,引入库,使有pprof的能力
    )

    浏览器访问:file:///private/var/folders/w9/l38fmd696n95tmrt4pf980vm0000gn/T/pprof001.svg

    标准库文档:https://studygolang.com/pkgdoc

    或者使用:godoc -http localhost:6060,在本地查看

    :

    赞赏码

    非学,无以致疑;非问,无以广识

  • 相关阅读:
    在Ubuntu中通过update-alternatives切换软件版本
    SCons: 替代 make 和 makefile 及 javac 的极好用的c、c++、java 构建工具
    mongodb 的使用
    利用grub从ubuntu找回windows启动项
    How to Repair GRUB2 When Ubuntu Won’t Boot
    Redis vs Mongo vs mysql
    java script 的工具
    python 的弹框
    how to use greendao in android studio
    python yield的终极解释
  • 原文地址:https://www.cnblogs.com/lxwphp/p/15452727.html
Copyright © 2011-2022 走看看