Go从0开发(10)_http/单元,基准测试


http-get 方法

package main

import (
   "fmt"
   "io/ioutil"
   "net/http"
   "net/url"
)

//get
func f1()  {
   resp,err := http.Get("http://127.0.0.1:9900/app/v3?name=132")
   if err != nil{
      fmt.Println(err.Error())
   }
   defer resp.Body.Close()
   b,err := ioutil.ReadAll(resp.Body)
   if err != nil{
      fmt.Println(err.Error())
   }
   fmt.Println(string(b))
}

//request
func f2()  {
   //请求参数编码
   data := url.Values{}
   data.Set("name","张三")
   data.Set("age","456")
   queryStr := data.Encode()
   fmt.Println(queryStr)

   url,err := url.Parse("http://127.0.0.1:9900/app/v3")
   if err != nil{
      fmt.Println(err)
   }
   url.RawQuery = queryStr //组装链接
   req,err := http.NewRequest("GET",url.String(),nil)
   if err != nil{
      fmt.Println(err)
   }

   defer req.Body.Close()
   resp,err := http.DefaultClient.Do(req)

   b,err := ioutil.ReadAll(resp.Body)
   if err != nil{
      fmt.Println(err.Error())
   }
   fmt.Println(string(b))

}

func f3()  {
   //请求参数编码
   data := url.Values{}
   data.Set("name","张三")
   data.Set("age","456")
   queryStr := data.Encode()
   fmt.Println(queryStr)

   url,err := url.Parse("http://127.0.0.1:9900/app/v3")
   req,err := http.NewRequest("GET",url.String(),nil)
   if err != nil{
      fmt.Println(err)
   }
   tr := &http.Transport{
      Proxy:                  nil,
      DialContext:            nil,
      Dial:                   nil,
      DialTLS:                nil,
      TLSClientConfig:        nil,
      TLSHandshakeTimeout:    0,
      DisableKeepAlives:      true,
      DisableCompression:     false,
      MaxIdleConns:           0,
      MaxIdleConnsPerHost:    0,
      MaxConnsPerHost:        0,
      IdleConnTimeout:        0,
      ResponseHeaderTimeout:  0,
      ExpectContinueTimeout:  0,
      TLSNextProt           nil,
      ProxyConnectHeader:     nil,
      MaxResponseHeaderBytes: 0,
      WriteBufferSize:        0,
      ReadBufferSize:         0,
      ForceAttemptHTTP2:      false,
   }

   client := http.Client{
      Transport:     tr,
      CheckRedirect: nil,
      Jar:           nil,
      Timeout:       0,
   }

   resp,err := client.Do(req)
   defer resp.Body.Close()
   b,err := ioutil.ReadAll(resp.Body)
   if err != nil{
      fmt.Println(err.Error())
   }
   fmt.Println(string(b))

}

func main()  {
   f3()
}

单元测试/基准测试

sun.go

package test_ser

func Fsum(a,b int) int {
return a+b
}

sun_test.go

package test_ser

import (
"reflect"
"testing"
)

//单元测试
func TestFsum(t *testing.T) {
x := Fsum(1,20)
y := 21
if !reflect.DeepEqual(x,y){
t.Errorf("x: %d | y: %d",x,y)
}
}

sum_bench_test.go

package test_ser

import "testing"

//基准测试
func BenchmarkSum(t *testing.B) {
for i:=0; i<t.N;i++ {
Fsum(1,20)
}
}

还有其他许多的 传送门 


伍先生
  • 职业: 程序员,产品
  • 码龄: 4.1
  • 技能: PHP Go 前端
  • 微信: JwCode
  • 公众号/小程序: 渐悟分享