Best K6 code snippet using httpext.Close
helpers_test.go
Source:helpers_test.go
...108 err := writer.WriteField("MultiPartPosted", "value")109 Equal(t, err, nil)110 // Don't forget to close the multipart writer.111 // If you don't close it, your request will be missing the terminating boundary.112 err = writer.Close()113 Equal(t, err, nil)114 test = new(TestStruct)115 r, _ = http.NewRequest(http.MethodPost, "/decode/13?id=12", body)116 r.Header.Set(httpext.ContentType, writer.FormDataContentType())117 w = httptest.NewRecorder()118 hf.ServeHTTP(w, r)119 Equal(t, w.Code, http.StatusOK)120 Equal(t, test.ID, 12)121 Equal(t, test.Posted, "")122 Equal(t, test.MultiPartPosted, "value")123 body = &bytes.Buffer{}124 writer = multipart.NewWriter(body)125 err = writer.WriteField("MultiPartPosted", "value")126 Equal(t, err, nil)127 // Don't forget to close the multipart writer.128 // If you don't close it, your request will be missing the terminating boundary.129 err = writer.Close()130 Equal(t, err, nil)131 test = new(TestStruct)132 r, _ = http.NewRequest(http.MethodPost, "/decode2/13", body)133 r.Header.Set(httpext.ContentType, writer.FormDataContentType())134 w = httptest.NewRecorder()135 hf.ServeHTTP(w, r)136 Equal(t, w.Code, http.StatusOK)137 Equal(t, test.ID, 0)138 Equal(t, test.Posted, "")139 Equal(t, test.MultiPartPosted, "value")140 body = &bytes.Buffer{}141 writer = multipart.NewWriter(body)142 err = writer.WriteField("MultiPartPosted", "value")143 Equal(t, err, nil)144 // Don't forget to close the multipart writer.145 // If you don't close it, your request will be missing the terminating boundary.146 err = writer.Close()147 Equal(t, err, nil)148 test = new(TestStruct)149 r, _ = http.NewRequest(http.MethodPost, "/decode3/11", body)150 r.Header.Set(httpext.ContentType, writer.FormDataContentType())151 w = httptest.NewRecorder()152 hf.ServeHTTP(w, r)153 Equal(t, w.Code, http.StatusOK)154 Equal(t, test.ID, 11)155 Equal(t, test.Posted, "")156 Equal(t, test.MultiPartPosted, "value")157 jsonBody := `{"ID":13,"Posted":"value","MultiPartPosted":"value"}`158 test = new(TestStruct)159 r, _ = http.NewRequest(http.MethodPost, "/decode/13", strings.NewReader(jsonBody))160 r.Header.Set(httpext.ContentType, httpext.ApplicationJSON)161 w = httptest.NewRecorder()162 hf.ServeHTTP(w, r)163 Equal(t, w.Code, http.StatusOK)164 Equal(t, test.ID, 13)165 Equal(t, test.Posted, "value")166 Equal(t, test.MultiPartPosted, "value")167 test = new(TestStruct)168 r, _ = http.NewRequest(http.MethodPost, "/decode/13?id=14", strings.NewReader(jsonBody))169 r.Header.Set(httpext.ContentType, httpext.ApplicationJSON)170 w = httptest.NewRecorder()171 hf.ServeHTTP(w, r)172 Equal(t, w.Code, http.StatusOK)173 Equal(t, test.ID, 14)174 Equal(t, test.Posted, "value")175 Equal(t, test.MultiPartPosted, "value")176 var buff bytes.Buffer177 gzw := gzip.NewWriter(&buff)178 defer func() {179 _ = gzw.Close()180 }()181 _, err = gzw.Write([]byte(jsonBody))182 Equal(t, err, nil)183 err = gzw.Close()184 Equal(t, err, nil)185 test = new(TestStruct)186 r, _ = http.NewRequest(http.MethodPost, "/decode/13?id=14", &buff)187 r.Header.Set(httpext.ContentType, httpext.ApplicationJSON)188 r.Header.Set(httpext.ContentEncoding, httpext.Gzip)189 w = httptest.NewRecorder()190 hf.ServeHTTP(w, r)191 Equal(t, w.Code, http.StatusOK)192 Equal(t, test.ID, 14)193 Equal(t, test.Posted, "value")194 Equal(t, test.MultiPartPosted, "value")195 test = new(TestStruct)196 r, _ = http.NewRequest(http.MethodPost, "/decode-noquery/13?id=14", strings.NewReader(jsonBody))197 r.Header.Set(httpext.ContentType, httpext.ApplicationJSON)198 w = httptest.NewRecorder()199 hf.ServeHTTP(w, r)200 Equal(t, w.Code, http.StatusOK)201 Equal(t, test.ID, 13)202 Equal(t, test.Posted, "value")203 Equal(t, test.MultiPartPosted, "value")204 xmlBody := `<TestStruct><ID>13</ID><Posted>value</Posted><MultiPartPosted>value</MultiPartPosted></TestStruct>`205 test = new(TestStruct)206 r, _ = http.NewRequest(http.MethodPost, "/decode/13", strings.NewReader(xmlBody))207 r.Header.Set(httpext.ContentType, httpext.ApplicationXML)208 w = httptest.NewRecorder()209 hf.ServeHTTP(w, r)210 Equal(t, w.Code, http.StatusOK)211 Equal(t, test.ID, 13)212 Equal(t, test.Posted, "value")213 Equal(t, test.MultiPartPosted, "value")214 test = new(TestStruct)215 r, _ = http.NewRequest(http.MethodPost, "/decode/13?id=14", strings.NewReader(xmlBody))216 r.Header.Set(httpext.ContentType, httpext.ApplicationXML)217 w = httptest.NewRecorder()218 hf.ServeHTTP(w, r)219 Equal(t, w.Code, http.StatusOK)220 Equal(t, test.ID, 14)221 Equal(t, test.Posted, "value")222 Equal(t, test.MultiPartPosted, "value")223 test = new(TestStruct)224 r, _ = http.NewRequest(http.MethodPost, "/decode-noquery/13?id=14", strings.NewReader(xmlBody))225 r.Header.Set(httpext.ContentType, httpext.ApplicationXML)226 w = httptest.NewRecorder()227 hf.ServeHTTP(w, r)228 Equal(t, w.Code, http.StatusOK)229 Equal(t, test.ID, 13)230 Equal(t, test.Posted, "value")231 Equal(t, test.MultiPartPosted, "value")232}233func TestDecodeQueryParams(t *testing.T) {234 type Test struct {235 ID int `form:"id"`236 }237 test := new(Test)238 p := New()239 p.Post("/decode-noquery/:id", func(w http.ResponseWriter, r *http.Request) {240 err := DecodeQueryParams(r, httpext.NoQueryParams, test)241 Equal(t, err, nil)242 })243 p.Post("/decode/:id", func(w http.ResponseWriter, r *http.Request) {244 err := DecodeQueryParams(r, httpext.QueryParams, test)245 Equal(t, err, nil)246 })247 hf := p.Serve()248 r, _ := http.NewRequest(http.MethodPost, "/decode/13?id=14", nil)249 w := httptest.NewRecorder()250 hf.ServeHTTP(w, r)251 Equal(t, w.Code, http.StatusOK)252 Equal(t, test.ID, 14) // 14 because 13 was added to the array of 'id' query params253 test = new(Test)254 r, _ = http.NewRequest(http.MethodPost, "/decode/13?otheridval=14", nil)255 w = httptest.NewRecorder()256 hf.ServeHTTP(w, r)257 Equal(t, w.Code, http.StatusOK)258 Equal(t, test.ID, 13)259 test = new(Test)260 r, _ = http.NewRequest(http.MethodPost, "/decode-noquery/13?id=14", nil)261 w = httptest.NewRecorder()262 hf.ServeHTTP(w, r)263 Equal(t, w.Code, http.StatusOK)264 Equal(t, test.ID, 14)265}266func TestDecodeSEOQueryParams(t *testing.T) {267 type Test struct {268 ID int `form:"id"`269 }270 test := new(Test)271 p := New()272 p.Post("/decode/:id", func(w http.ResponseWriter, r *http.Request) {273 err := DecodeSEOQueryParams(r, test)274 Equal(t, err, nil)275 })276 hf := p.Serve()277 r, _ := http.NewRequest(http.MethodPost, "/decode/13?id=14", nil)278 w := httptest.NewRecorder()279 hf.ServeHTTP(w, r)280 Equal(t, w.Code, http.StatusOK)281 Equal(t, test.ID, 13) // 13 because 14 isn;t part of the SEO query params282}283func TestAcceptedLanguages(t *testing.T) {284 req, _ := http.NewRequest("POST", "/", nil)285 req.Header.Set(httpext.AcceptedLanguage, "da, en-GB;q=0.8, en;q=0.7")286 languages := AcceptedLanguages(req)287 Equal(t, languages[0], "da")288 Equal(t, languages[1], "en-GB")289 Equal(t, languages[2], "en")290 req.Header.Del(httpext.AcceptedLanguage)291 languages = AcceptedLanguages(req)292 Equal(t, len(languages), 0)293 req.Header.Set(httpext.AcceptedLanguage, "")294 languages = AcceptedLanguages(req)295 Equal(t, len(languages), 0)296}297func TestAttachment(t *testing.T) {298 p := New()299 p.Get("/dl", func(w http.ResponseWriter, r *http.Request) {300 f, _ := os.Open("logo.png")301 if err := Attachment(w, f, "logo.png"); err != nil {302 panic(err)303 }304 })305 p.Get("/dl-unknown-type", func(w http.ResponseWriter, r *http.Request) {306 f, _ := os.Open("logo.png")307 if err := Attachment(w, f, "logo"); err != nil {308 panic(err)309 }310 })311 r, _ := http.NewRequest(http.MethodGet, "/dl", nil)312 w := &closeNotifyingRecorder{313 httptest.NewRecorder(),314 make(chan bool, 1),315 }316 hf := p.Serve()317 hf.ServeHTTP(w, r)318 Equal(t, w.Code, http.StatusOK)319 Equal(t, w.Header().Get(httpext.ContentDisposition), "attachment;filename=logo.png")320 Equal(t, w.Header().Get(httpext.ContentType), "image/png")321 Equal(t, w.Body.Len(), 20797)322 r, _ = http.NewRequest(http.MethodGet, "/dl-unknown-type", nil)323 w = &closeNotifyingRecorder{324 httptest.NewRecorder(),325 make(chan bool, 1),326 }327 hf = p.Serve()328 hf.ServeHTTP(w, r)329 Equal(t, w.Code, http.StatusOK)330 Equal(t, w.Header().Get(httpext.ContentDisposition), "attachment;filename=logo")331 Equal(t, w.Header().Get(httpext.ContentType), "application/octet-stream")332 Equal(t, w.Body.Len(), 20797)333}334func TestInline(t *testing.T) {335 p := New()336 p.Get("/dl-inline", func(w http.ResponseWriter, r *http.Request) {337 f, _ := os.Open("logo.png")338 if err := Inline(w, f, "logo.png"); err != nil {339 panic(err)340 }341 })342 p.Get("/dl-unknown-type-inline", func(w http.ResponseWriter, r *http.Request) {343 f, _ := os.Open("logo.png")344 if err := Inline(w, f, "logo"); err != nil {345 panic(err)346 }347 })348 r, _ := http.NewRequest(http.MethodGet, "/dl-inline", nil)349 w := &closeNotifyingRecorder{350 httptest.NewRecorder(),351 make(chan bool, 1),352 }353 hf := p.Serve()354 hf.ServeHTTP(w, r)355 Equal(t, w.Code, http.StatusOK)356 Equal(t, w.Header().Get(httpext.ContentDisposition), "inline;filename=logo.png")357 Equal(t, w.Header().Get(httpext.ContentType), "image/png")358 Equal(t, w.Body.Len(), 20797)359 r, _ = http.NewRequest(http.MethodGet, "/dl-unknown-type-inline", nil)360 w = &closeNotifyingRecorder{361 httptest.NewRecorder(),362 make(chan bool, 1),363 }364 hf = p.Serve()365 hf.ServeHTTP(w, r)366 Equal(t, w.Code, http.StatusOK)367 Equal(t, w.Header().Get(httpext.ContentDisposition), "inline;filename=logo")368 Equal(t, w.Header().Get(httpext.ContentType), "application/octet-stream")369 Equal(t, w.Body.Len(), 20797)370}371func TestClientIP(t *testing.T) {372 req, _ := http.NewRequest("POST", "/", nil)373 req.Header.Set("X-Real-IP", " 10.10.10.10 ")374 req.Header.Set("X-Forwarded-For", " 20.20.20.20, 30.30.30.30")375 req.RemoteAddr = " 40.40.40.40:42123 "376 Equal(t, ClientIP(req), "10.10.10.10")377 req.Header.Del("X-Real-IP")378 Equal(t, ClientIP(req), "20.20.20.20")379 req.Header.Set("X-Forwarded-For", "30.30.30.30 ")380 Equal(t, ClientIP(req), "30.30.30.30")381 req.Header.Del("X-Forwarded-For")382 Equal(t, ClientIP(req), "40.40.40.40")383}384func TestJSON(t *testing.T) {385 jsonData := `{"id":1,"name":"Patient Zero"}`386 callbackFunc := "CallbackFunc"387 p := New()388 p.Use(Gzip2)389 p.Get("/jsonstream", func(w http.ResponseWriter, r *http.Request) {390 if err := JSONStream(w, http.StatusOK, zombie{1, "Patient Zero"}); err != nil {391 panic(err)392 }393 })394 p.Get("/json", func(w http.ResponseWriter, r *http.Request) {395 if err := JSON(w, http.StatusOK, zombie{1, "Patient Zero"}); err != nil {396 panic(err)397 }398 })399 p.Get("/badjson", func(w http.ResponseWriter, r *http.Request) {400 if err := JSON(w, http.StatusOK, func() {}); err != nil {401 http.Error(w, err.Error(), http.StatusInternalServerError)402 }403 })404 p.Get("/jsonbytes", func(w http.ResponseWriter, r *http.Request) {405 b, _ := json.Marshal("Patient Zero")406 if err := JSONBytes(w, http.StatusOK, b); err != nil {407 panic(err)408 }409 })410 p.Get("/jsonp", func(w http.ResponseWriter, r *http.Request) {411 if err := JSONP(w, http.StatusOK, zombie{1, "Patient Zero"}, callbackFunc); err != nil {412 panic(err)413 }414 })415 p.Get("/badjsonp", func(w http.ResponseWriter, r *http.Request) {416 if err := JSONP(w, http.StatusOK, func() {}, callbackFunc); err != nil {417 http.Error(w, err.Error(), http.StatusInternalServerError)418 }419 })420 hf := p.Serve()421 r, _ := http.NewRequest(http.MethodGet, "/jsonstream", nil)422 w := httptest.NewRecorder()423 hf.ServeHTTP(w, r)424 Equal(t, w.Code, http.StatusOK)425 Equal(t, w.Header().Get(httpext.ContentType), httpext.ApplicationJSON)426 Equal(t, w.Body.String(), jsonData+"\n")427 r, _ = http.NewRequest(http.MethodGet, "/json", nil)428 w = httptest.NewRecorder()429 hf.ServeHTTP(w, r)430 Equal(t, w.Code, http.StatusOK)431 Equal(t, w.Header().Get(httpext.ContentType), httpext.ApplicationJSON)432 Equal(t, w.Body.String(), jsonData)433 r, _ = http.NewRequest(http.MethodGet, "/badjson", nil)434 w = httptest.NewRecorder()435 hf.ServeHTTP(w, r)436 Equal(t, w.Code, http.StatusInternalServerError)437 Equal(t, w.Header().Get(httpext.ContentType), httpext.TextPlain)438 Equal(t, w.Body.String(), "json: unsupported type: func()\n")439 r, _ = http.NewRequest(http.MethodGet, "/jsonbytes", nil)440 w = httptest.NewRecorder()441 hf.ServeHTTP(w, r)442 Equal(t, w.Code, http.StatusOK)443 Equal(t, w.Header().Get(httpext.ContentType), httpext.ApplicationJSON)444 Equal(t, w.Body.String(), "\"Patient Zero\"")445 r, _ = http.NewRequest(http.MethodGet, "/jsonp", nil)446 w = httptest.NewRecorder()447 hf.ServeHTTP(w, r)448 Equal(t, w.Code, http.StatusOK)449 Equal(t, w.Header().Get(httpext.ContentType), httpext.ApplicationJSON)450 Equal(t, w.Body.String(), callbackFunc+"("+jsonData+");")451 r, _ = http.NewRequest(http.MethodGet, "/badjsonp", nil)452 w = httptest.NewRecorder()453 hf.ServeHTTP(w, r)454 Equal(t, w.Code, http.StatusInternalServerError)455 Equal(t, w.Header().Get(httpext.ContentType), httpext.TextPlain)456 Equal(t, w.Body.String(), "json: unsupported type: func()\n")457}458func TestXML(t *testing.T) {459 xmlData := `<zombie><id>1</id><name>Patient Zero</name></zombie>`460 p := New()461 p.Use(Gzip2)462 p.Get("/xml", func(w http.ResponseWriter, r *http.Request) {463 if err := XML(w, http.StatusOK, zombie{1, "Patient Zero"}); err != nil {464 panic(err)465 }466 })467 p.Get("/badxml", func(w http.ResponseWriter, r *http.Request) {468 if err := XML(w, http.StatusOK, func() {}); err != nil {469 http.Error(w, err.Error(), http.StatusInternalServerError)470 }471 })472 p.Get("/xmlbytes", func(w http.ResponseWriter, r *http.Request) {473 b, _ := xml.Marshal(zombie{1, "Patient Zero"})474 if err := XMLBytes(w, http.StatusOK, b); err != nil {475 panic(err)476 }477 })478 hf := p.Serve()479 r, _ := http.NewRequest(http.MethodGet, "/xml", nil)480 w := httptest.NewRecorder()481 hf.ServeHTTP(w, r)482 Equal(t, w.Code, http.StatusOK)483 Equal(t, w.Header().Get(httpext.ContentType), httpext.ApplicationXML)484 Equal(t, w.Body.String(), xml.Header+xmlData)485 r, _ = http.NewRequest(http.MethodGet, "/xmlbytes", nil)486 w = httptest.NewRecorder()487 hf.ServeHTTP(w, r)488 Equal(t, w.Code, http.StatusOK)489 Equal(t, w.Header().Get(httpext.ContentType), httpext.ApplicationXML)490 Equal(t, w.Body.String(), xml.Header+xmlData)491 r, _ = http.NewRequest(http.MethodGet, "/badxml", nil)492 w = httptest.NewRecorder()493 hf.ServeHTTP(w, r)494 Equal(t, w.Code, http.StatusInternalServerError)495 Equal(t, w.Header().Get(httpext.ContentType), httpext.TextPlain)496 Equal(t, w.Body.String(), "xml: unsupported type: func()\n")497}498func TestBadParseForm(t *testing.T) {499 // successful scenarios tested under TestDecode500 p := New()501 p.Get("/users/:id", func(w http.ResponseWriter, r *http.Request) {502 if err := ParseForm(r); err != nil {503 if _, errr := w.Write([]byte(err.Error())); errr != nil {504 panic(errr)505 }506 return507 }508 })509 code, body := request(http.MethodGet, "/users/16?test=%2f%%efg", p)510 Equal(t, code, http.StatusOK)511 Equal(t, body, "invalid URL escape \"%%e\"")512}513func TestBadParseMultiPartForm(t *testing.T) {514 // successful scenarios tested under TestDecode515 p := New()516 p.Get("/users/:id", func(w http.ResponseWriter, r *http.Request) {517 if err := ParseMultipartForm(r, 10<<5); err != nil {518 if _, errr := w.Write([]byte(err.Error())); errr != nil {519 panic(err)520 }521 return522 }523 })524 code, body := requestMultiPart(http.MethodGet, "/users/16?test=%2f%%efg", p)525 Equal(t, code, http.StatusOK)526 Equal(t, body, "invalid URL escape \"%%e\"")527}528func TestEncodeToURLValues(t *testing.T) {529 type Test struct {530 Domain string `form:"domain"`531 Next string `form:"next"`532 }533 s := Test{Domain: "company.org", Next: "NIDEJ89#(@#NWJK"}534 values, err := EncodeToURLValues(s)535 Equal(t, err, nil)536 Equal(t, len(values), 2)537 Equal(t, values.Encode(), "domain=company.org&next=NIDEJ89%23%28%40%23NWJK")538}539type gzipWriter struct {540 io.Writer541 http.ResponseWriter542 sniffComplete bool543}544func (w *gzipWriter) Write(b []byte) (int, error) {545 if !w.sniffComplete {546 if w.Header().Get(httpext.ContentType) == "" {547 w.Header().Set(httpext.ContentType, http.DetectContentType(b))548 }549 w.sniffComplete = true550 }551 return w.Writer.Write(b)552}553func (w *gzipWriter) Flush() error {554 return w.Writer.(*gzip.Writer).Flush()555}556func (w *gzipWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {557 return w.ResponseWriter.(http.Hijacker).Hijack()558}559var gzipPool = sync.Pool{560 New: func() interface{} {561 return &gzipWriter{Writer: gzip.NewWriter(ioutil.Discard)}562 },563}564// Gzip returns a middleware which compresses HTTP response using gzip compression565// scheme.566func Gzip2(next http.HandlerFunc) http.HandlerFunc {567 return func(w http.ResponseWriter, r *http.Request) {568 var gz *gzipWriter569 var gzr *gzip.Writer570 w.Header().Add(httpext.Vary, httpext.AcceptEncoding)571 if strings.Contains(r.Header.Get(httpext.AcceptEncoding), httpext.Gzip) {572 gz = gzipPool.Get().(*gzipWriter)573 gz.sniffComplete = false574 gzr = gz.Writer.(*gzip.Writer)575 gzr.Reset(w)576 gz.ResponseWriter = w577 w.Header().Set(httpext.ContentEncoding, httpext.Gzip)578 w = gz579 defer func() {580 // fmt.Println(gz.sniffComplete)581 if !gz.sniffComplete {582 // We have to reset response to it's pristine state when583 // nothing is written to body.584 w.Header().Del(httpext.ContentEncoding)585 gzr.Reset(ioutil.Discard)586 }587 gzr.Close()588 gzipPool.Put(gz)589 }()590 }591 next(w, r)592 }593}...
gzip_test.go
Source:gzip_test.go
...31 })32 p.Get("/empty", func(w http.ResponseWriter, r *http.Request) {33 })34 server := httptest.NewServer(p.Serve())35 defer server.Close()36 req, _ := http.NewRequest(http.MethodGet, server.URL+"/test", nil)37 client := &http.Client{}38 resp, err := client.Do(req)39 Equal(t, err, nil)40 Equal(t, resp.StatusCode, http.StatusOK)41 b, err := ioutil.ReadAll(resp.Body)42 Equal(t, err, nil)43 Equal(t, string(b), "test")44 req, _ = http.NewRequest(http.MethodGet, server.URL+"/test", nil)45 req.Header.Set(httpext.AcceptEncoding, "gzip")46 resp, err = client.Do(req)47 Equal(t, err, nil)48 Equal(t, resp.StatusCode, http.StatusOK)49 Equal(t, resp.Header.Get(httpext.ContentEncoding), httpext.Gzip)50 Equal(t, resp.Header.Get(httpext.ContentType), httpext.TextPlain)51 r, err := gzip.NewReader(resp.Body)52 Equal(t, err, nil)53 defer r.Close()54 b, err = ioutil.ReadAll(r)55 Equal(t, err, nil)56 Equal(t, string(b), "test")57 req, _ = http.NewRequest(http.MethodGet, server.URL+"/empty", nil)58 resp, err = client.Do(req)59 Equal(t, err, nil)60 Equal(t, resp.StatusCode, http.StatusOK)61}62func TestGzipLevel(t *testing.T) {63 // bad gzip level64 PanicMatches(t, func() { GzipLevel(999) }, "gzip: invalid compression level: 999")65 p := pure.New()66 p.Use(GzipLevel(flate.BestCompression))67 p.Get("/test", func(w http.ResponseWriter, r *http.Request) {68 _, _ = w.Write([]byte("test"))69 })70 p.Get("/empty", func(w http.ResponseWriter, r *http.Request) {71 })72 server := httptest.NewServer(p.Serve())73 defer server.Close()74 req, _ := http.NewRequest(http.MethodGet, server.URL+"/test", nil)75 client := &http.Client{}76 resp, err := client.Do(req)77 Equal(t, err, nil)78 Equal(t, resp.StatusCode, http.StatusOK)79 b, err := ioutil.ReadAll(resp.Body)80 Equal(t, err, nil)81 Equal(t, string(b), "test")82 req, _ = http.NewRequest(http.MethodGet, server.URL+"/test", nil)83 req.Header.Set(httpext.AcceptEncoding, "gzip")84 resp, err = client.Do(req)85 Equal(t, err, nil)86 Equal(t, resp.StatusCode, http.StatusOK)87 Equal(t, resp.Header.Get(httpext.ContentEncoding), httpext.Gzip)88 Equal(t, resp.Header.Get(httpext.ContentType), httpext.TextPlain)89 r, err := gzip.NewReader(resp.Body)90 Equal(t, err, nil)91 defer r.Close()92 b, err = ioutil.ReadAll(r)93 Equal(t, err, nil)94 Equal(t, string(b), "test")95 req, _ = http.NewRequest(http.MethodGet, server.URL+"/empty", nil)96 resp, err = client.Do(req)97 Equal(t, err, nil)98 Equal(t, resp.StatusCode, http.StatusOK)99}100func TestGzipFlush(t *testing.T) {101 rec := httptest.NewRecorder()102 buff := new(bytes.Buffer)103 w := gzip.NewWriter(buff)104 gw := gzipWriter{Writer: w, ResponseWriter: rec}105 Equal(t, buff.Len(), 0)106 err := gw.Flush()107 Equal(t, err, nil)108 n1 := buff.Len()109 NotEqual(t, n1, 0)110 _, err = gw.Write([]byte("x"))111 Equal(t, err, nil)112 n2 := buff.Len()113 Equal(t, n1, n2)114 err = gw.Flush()115 Equal(t, err, nil)116 NotEqual(t, n2, buff.Len())117}118func TestGzipHijack(t *testing.T) {119 rec := newCloseNotifyingRecorder()120 buf := new(bytes.Buffer)121 w := gzip.NewWriter(buf)122 gw := gzipWriter{Writer: w, ResponseWriter: rec}123 _, bufrw, err := gw.Hijack()124 Equal(t, err, nil)125 _, _ = bufrw.WriteString("test")126}127type closeNotifyingRecorder struct {128 *httptest.ResponseRecorder129 closed chan bool130}131func newCloseNotifyingRecorder() *closeNotifyingRecorder {132 return &closeNotifyingRecorder{133 httptest.NewRecorder(),134 make(chan bool, 1),135 }136}137func (c *closeNotifyingRecorder) Close() {138 c.closed <- true139}140func (c *closeNotifyingRecorder) CloseNotify() <-chan bool {141 return c.closed142}143func (c *closeNotifyingRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) {144 reader := bufio.NewReader(c.Body)145 writer := bufio.NewWriter(c.Body)146 return nil, bufio.NewReadWriter(reader, writer), nil147}...
gzip.go
Source:gzip.go
...55 // nothing is written to body.56 w.Header().Del(httpext.ContentEncoding)57 gzr.Reset(ioutil.Discard)58 }59 gzr.Close()60 gzipPool.Put(gz)61 }()62 }63 next(w, r)64 }65}66// GzipLevel returns a middleware which compresses HTTP response using gzip compression67// scheme using the level specified68func GzipLevel(level int) pure.Middleware {69 // test gzip level, then don't have to each time one is created70 // in the pool71 if _, err := gzip.NewWriterLevel(ioutil.Discard, level); err != nil {72 panic(err)73 }74 var gzipPool = sync.Pool{75 New: func() interface{} {76 z, _ := gzip.NewWriterLevel(ioutil.Discard, level)77 return &gzipWriter{Writer: z}78 },79 }80 return func(next http.HandlerFunc) http.HandlerFunc {81 return func(w http.ResponseWriter, r *http.Request) {82 w.Header().Add(httpext.Vary, httpext.AcceptEncoding)83 if strings.Contains(r.Header.Get(httpext.AcceptEncoding), httpext.Gzip) {84 gz := gzipPool.Get().(*gzipWriter)85 gz.sniffComplete = false86 gzr := gz.Writer.(*gzip.Writer)87 gzr.Reset(w)88 gz.ResponseWriter = w89 w.Header().Set(httpext.ContentEncoding, httpext.Gzip)90 w = gz91 defer func() {92 if !gz.sniffComplete {93 // We have to reset response to it's pristine state when94 // nothing is written to body.95 w.Header().Del(httpext.ContentEncoding)96 gzr.Reset(ioutil.Discard)97 }98 gzr.Close()99 gzipPool.Put(gz)100 }()101 }102 next(w, r)103 }104 }105}...
Close
Using AI Code Generation
1import (2func main() {3 if err != nil {4 fmt.Println("Error:", err)5 }6 defer resp.Body.Close()7 fmt.Println("Response Status:", resp.Status)8 fmt.Println("Response Headers:", resp.Header)9}10Response Headers: map[Alt-Svc:[quic=":443"; ma=2592000; v="46,43,39"] Cache-Control:[private, max-age=0] Content-Type:[text/html; charset=ISO-8859-1] Date:[Thu, 15 Mar 2018 16:25:57 GMT] Expires:[-1] P3p:[CP="This is not a P3P policy! See g.co/p3phelp for more info."] Server:[gws] Set-Cookie:[NID=135=Iv1S9XKJ0n0r5rMf2Q6YkYj7JdZp1CZc8OjKJg9h9a6vB3Vg5UJp0u6qB3fZ5l6Z0n0R5J5X2QbLJFgFk8mYRwQaP2xvPjWnZgDp; expires=Fri, 14-Sep-2018 16:25:57 GMT; path=/; domain=.google.com; HttpOnly] Vary:[Accept-Encoding] X-Frame-Options:[SAMEORIGIN] X-Xss-Protection:[1; mode=block]]11import (12func main() {13 if err != nil {14 fmt.Println("Error:", err)15 }16 defer resp.Body.Close()17 body, err := ioutil.ReadAll(resp.Body)18 if err != nil {19 fmt.Println("Error:", err)20 }21 fmt.Println("Response Body:", string(body))22}
Close
Using AI Code Generation
1import (2func main() {3 if err != nil {4 log.Fatalln(err)5 }6 defer resp.Body.Close()7 body, err := ioutil.ReadAll(resp.Body)8 if err != nil {9 log.Fatalln(err)10 }11 fmt.Println(string(body))12}
Close
Using AI Code Generation
1func main() {2 if err != nil {3 log.Fatal(err)4 }5 client := &http.Client{}6 resp, err := client.Do(req)7 if err != nil {8 log.Fatal(err)9 }10 defer resp.Body.Close()11 fmt.Println("response Status:", resp.Status)12 fmt.Println("response Headers:", resp.Header)13 body, err := ioutil.ReadAll(resp.Body)14 if err != nil {15 log.Fatal(err)16 }17 fmt.Println("response Body:", string(body))18}19response Headers: map[Accept-Ranges:[bytes] Age:[1] Cache-Control:[max-age=604800] Content-Encoding:[gzip] Content-Type:[text/html; charset=utf-8] Date:[Mon, 13 Apr 2020 16:37:04 GMT] Etag:["604a0d0d-1e5a"] Expires:[Mon, 20 Apr 2020 16:37:04 GMT] Last-Modified:[Fri, 17 Oct 2019 07:18:05 GMT] Server:[ECS (dcb/7A0A)] Vary:[Accept-Encoding] X-Cache:[HIT] X-Content-Type-Options:[nosniff] X-Frame-Options:[SAMEORIGIN] X-Xss-Protection:[1; mode=block]]
Close
Using AI Code Generation
1import (2func main() {3 client := &http.Client{}4 if err != nil {5 fmt.Println(err)6 }7 resp, err := client.Do(req)8 if err != nil {9 fmt.Println(err)10 } else {11 fmt.Println("Response status:", resp.Status)12 resp.Body.Close()13 }14}
Close
Using AI Code Generation
1import (2func main() {3 beego.Run()4}5import (6func main() {7 beego.Run()8}
Close
Using AI Code Generation
1import (2func main() {3 fmt.Println(resp)4 resp.Body.Close()5 fmt.Println(resp)6}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!