1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
|
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"reflect"
"time"
"github.com/valyala/fasthttp"
)
var headerContentTypeJson = []byte("application/json")
var client *fasthttp.Client
type Entity struct {
Name string
Id int
}
func main() {
// You may read the timeouts from some config
readTimeout, _ := time.ParseDuration("500ms")
writeTimeout, _ := time.ParseDuration("500ms")
maxIdleConnDuration, _ := time.ParseDuration("1h")
client = &fasthttp.Client{
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
MaxIdleConnDuration: maxIdleConnDuration,
NoDefaultUserAgentHeader: true, // Don't send: User-Agent: fasthttp
DisableHeaderNamesNormalizing: true, // If you set the case on your headers correctly you can enable this
DisablePathNormalizing: true,
// increase DNS cache time to an hour instead of default minute
Dial: (&fasthttp.TCPDialer{
Concurrency: 4096,
DNSCacheDuration: time.Hour,
}).Dial,
}
sendGetRequest()
sendPostRequest()
}
func sendGetRequest() {
req := fasthttp.AcquireRequest()
req.SetRequestURI("http://localhost:8080/")
req.Header.SetMethod(fasthttp.MethodGet)
resp := fasthttp.AcquireResponse()
err := client.Do(req, resp)
fasthttp.ReleaseRequest(req)
if err == nil {
fmt.Printf("DEBUG Response: %s\n", resp.Body())
} else {
fmt.Fprintf(os.Stderr, "ERR Connection error: %v\n", err)
}
fasthttp.ReleaseResponse(resp)
}
func sendPostRequest() {
// per-request timeout
reqTimeout := time.Duration(100) * time.Millisecond
reqEntity := &Entity{
Name: "New entity",
}
reqEntityBytes, _ := json.Marshal(reqEntity)
req := fasthttp.AcquireRequest()
req.SetRequestURI("http://localhost:8080/")
req.Header.SetMethod(fasthttp.MethodPost)
req.Header.SetContentTypeBytes(headerContentTypeJson)
req.SetBodyRaw(reqEntityBytes)
resp := fasthttp.AcquireResponse()
err := client.DoTimeout(req, resp, reqTimeout)
fasthttp.ReleaseRequest(req)
defer fasthttp.ReleaseResponse(resp)
if err != nil {
errName, known := httpConnError(err)
if known {
fmt.Fprintf(os.Stderr, "WARN conn error: %v\n", errName)
} else {
fmt.Fprintf(os.Stderr, "ERR conn failure: %v %v\n", errName, err)
}
return
}
statusCode := resp.StatusCode()
respBody := resp.Body()
fmt.Printf("DEBUG Response: %s\n", respBody)
if statusCode != http.StatusOK {
fmt.Fprintf(os.Stderr, "ERR invalid HTTP response code: %d\n", statusCode)
return
}
respEntity := &Entity{}
err = json.Unmarshal(respBody, respEntity)
if err == nil || errors.Is(err, io.EOF) {
fmt.Printf("DEBUG Parsed Response: %v\n", respEntity)
} else {
fmt.Fprintf(os.Stderr, "ERR failed to parse response: %v\n", err)
}
}
func httpConnError(err error) (string, bool) {
var (
errName string
known = true
)
switch {
case errors.Is(err, fasthttp.ErrTimeout):
errName = "timeout"
case errors.Is(err, fasthttp.ErrNoFreeConns):
errName = "conn_limit"
case errors.Is(err, fasthttp.ErrConnectionClosed):
errName = "conn_close"
case reflect.TypeOf(err).String() == "*net.OpError":
errName = "timeout"
default:
known = false
}
return errName, known
}
|