How to use NewResponse method of httpext Package

Best K6 code snippet using httpext.NewResponse

request.go

Source:request.go Github

copy

Full Screen

...64 if state.Options.Throw.Bool {65 return nil, err66 }67 state.Logger.WithField("error", err).Warn("Request Failed")68 r := httpext.NewResponse()69 r.Error = err.Error()70 var k6e httpext.K6Error71 if errors.As(err, &k6e) {72 r.ErrorCode = int(k6e.Code)73 }74 return &Response{Response: r, client: c}, nil75 }76 resp, err := httpext.MakeRequest(c.moduleInstance.vu.Context(), state, req)77 if err != nil {78 return nil, err79 }80 c.processResponse(resp, req.ResponseType)81 return c.responseFromHTTPext(resp), nil82}83// processResponse stores the body as an ArrayBuffer if indicated by84// respType. This is done here instead of in httpext.readResponseBody to avoid85// a reverse dependency on js/common or goja.86func (c *Client) processResponse(resp *httpext.Response, respType httpext.ResponseType) {87 if respType == httpext.ResponseTypeBinary && resp.Body != nil {88 resp.Body = c.moduleInstance.vu.Runtime().NewArrayBuffer(resp.Body.([]byte))89 }90}91func (c *Client) responseFromHTTPext(resp *httpext.Response) *Response {92 return &Response{Response: resp, client: c}93}94// TODO: break this function up95//nolint: gocyclo, cyclop, funlen, gocognit96func (c *Client) parseRequest(97 method string, reqURL, body interface{}, params goja.Value,98) (*httpext.ParsedHTTPRequest, error) {99 rt := c.moduleInstance.vu.Runtime()100 state := c.moduleInstance.vu.State()101 if state == nil {102 return nil, ErrHTTPForbiddenInInitContext103 }104 if urlJSValue, ok := reqURL.(goja.Value); ok {105 reqURL = urlJSValue.Export()106 }107 u, err := httpext.ToURL(reqURL)108 if err != nil {109 return nil, err110 }111 result := &httpext.ParsedHTTPRequest{112 URL: &u,113 Req: &http.Request{114 Method: method,115 URL: u.GetURL(),116 Header: make(http.Header),117 },118 Timeout: 60 * time.Second,119 Throw: state.Options.Throw.Bool,120 Redirects: state.Options.MaxRedirects,121 Cookies: make(map[string]*httpext.HTTPRequestCookie),122 Tags: make(map[string]string),123 ResponseCallback: c.responseCallback,124 }125 if state.Options.DiscardResponseBodies.Bool {126 result.ResponseType = httpext.ResponseTypeNone127 } else {128 result.ResponseType = httpext.ResponseTypeText129 }130 formatFormVal := func(v interface{}) string {131 // TODO: handle/warn about unsupported/nested values132 return fmt.Sprintf("%v", v)133 }134 handleObjectBody := func(data map[string]interface{}) error {135 if !requestContainsFile(data) {136 bodyQuery := make(url.Values, len(data))137 for k, v := range data {138 if arr, ok := v.([]interface{}); ok {139 for _, el := range arr {140 bodyQuery.Add(k, formatFormVal(el))141 }142 continue143 }144 bodyQuery.Set(k, formatFormVal(v))145 }146 result.Body = bytes.NewBufferString(bodyQuery.Encode())147 result.Req.Header.Set("Content-Type", "application/x-www-form-urlencoded")148 return nil149 }150 // handling multipart request151 result.Body = &bytes.Buffer{}152 mpw := multipart.NewWriter(result.Body)153 // For parameters of type common.FileData, created with open(file, "b"),154 // we write the file boundary to the body buffer.155 // Otherwise parameters are treated as standard form field.156 for k, v := range data {157 switch ve := v.(type) {158 case FileData:159 // writing our own part to handle receiving160 // different content-type than the default application/octet-stream161 h := make(textproto.MIMEHeader)162 escapedFilename := escapeQuotes(ve.Filename)163 h.Set("Content-Disposition",164 fmt.Sprintf(`form-data; name="%s"; filename="%s"`,165 k, escapedFilename))166 h.Set("Content-Type", ve.ContentType)167 // this writer will be closed either by the next part or168 // the call to mpw.Close()169 fw, err := mpw.CreatePart(h)170 if err != nil {171 return err172 }173 if _, err := fw.Write(ve.Data); err != nil {174 return err175 }176 default:177 fw, err := mpw.CreateFormField(k)178 if err != nil {179 return err180 }181 if _, err := fw.Write([]byte(formatFormVal(v))); err != nil {182 return err183 }184 }185 }186 if err := mpw.Close(); err != nil {187 return err188 }189 result.Req.Header.Set("Content-Type", mpw.FormDataContentType())190 return nil191 }192 if body != nil {193 switch data := body.(type) {194 case map[string]goja.Value:195 // TODO: fix forms submission and serialization in k6/html before fixing this..196 newData := map[string]interface{}{}197 for k, v := range data {198 newData[k] = v.Export()199 }200 if err := handleObjectBody(newData); err != nil {201 return nil, err202 }203 case goja.ArrayBuffer:204 result.Body = bytes.NewBuffer(data.Bytes())205 case map[string]interface{}:206 if err := handleObjectBody(data); err != nil {207 return nil, err208 }209 case string:210 result.Body = bytes.NewBufferString(data)211 case []byte:212 result.Body = bytes.NewBuffer(data)213 default:214 return nil, fmt.Errorf("unknown request body type %T", body)215 }216 }217 result.Req.Header.Set("User-Agent", state.Options.UserAgent.String)218 if state.CookieJar != nil {219 result.ActiveJar = state.CookieJar220 }221 // TODO: ditch goja.Value, reflections and Object and use a simple go map and type assertions?222 if params != nil && !goja.IsUndefined(params) && !goja.IsNull(params) {223 params := params.ToObject(rt)224 for _, k := range params.Keys() {225 switch k {226 case "cookies":227 cookiesV := params.Get(k)228 if goja.IsUndefined(cookiesV) || goja.IsNull(cookiesV) {229 continue230 }231 cookies := cookiesV.ToObject(rt)232 if cookies == nil {233 continue234 }235 for _, key := range cookies.Keys() {236 cookieV := cookies.Get(key)237 if goja.IsUndefined(cookieV) || goja.IsNull(cookieV) {238 continue239 }240 switch cookieV.ExportType() {241 case reflect.TypeOf(map[string]interface{}{}):242 result.Cookies[key] = &httpext.HTTPRequestCookie{Name: key, Value: "", Replace: false}243 cookie := cookieV.ToObject(rt)244 for _, attr := range cookie.Keys() {245 switch strings.ToLower(attr) {246 case "replace":247 result.Cookies[key].Replace = cookie.Get(attr).ToBoolean()248 case "value":249 result.Cookies[key].Value = cookie.Get(attr).String()250 }251 }252 default:253 result.Cookies[key] = &httpext.HTTPRequestCookie{Name: key, Value: cookieV.String(), Replace: false}254 }255 }256 case "headers":257 headersV := params.Get(k)258 if goja.IsUndefined(headersV) || goja.IsNull(headersV) {259 continue260 }261 headers := headersV.ToObject(rt)262 if headers == nil {263 continue264 }265 for _, key := range headers.Keys() {266 str := headers.Get(key).String()267 if strings.ToLower(key) == "host" {268 result.Req.Host = str269 }270 result.Req.Header.Set(key, str)271 }272 case "jar":273 jarV := params.Get(k)274 if goja.IsUndefined(jarV) || goja.IsNull(jarV) {275 continue276 }277 switch v := jarV.Export().(type) {278 case *CookieJar:279 result.ActiveJar = v.Jar280 }281 case "compression":282 algosString := strings.TrimSpace(params.Get(k).ToString().String())283 if algosString == "" {284 continue285 }286 algos := strings.Split(algosString, ",")287 var err error288 result.Compressions = make([]httpext.CompressionType, len(algos))289 for index, algo := range algos {290 algo = strings.TrimSpace(algo)291 result.Compressions[index], err = httpext.CompressionTypeString(algo)292 if err != nil {293 return nil, fmt.Errorf("unknown compression algorithm %s, supported algorithms are %s",294 algo, httpext.CompressionTypeValues())295 }296 }297 case "redirects":298 result.Redirects = null.IntFrom(params.Get(k).ToInteger())299 case "tags":300 tagsV := params.Get(k)301 if goja.IsUndefined(tagsV) || goja.IsNull(tagsV) {302 continue303 }304 tagObj := tagsV.ToObject(rt)305 if tagObj == nil {306 continue307 }308 for _, key := range tagObj.Keys() {309 result.Tags[key] = tagObj.Get(key).String()310 }311 case "auth":312 result.Auth = params.Get(k).String()313 case "timeout":314 t, err := types.GetDurationValue(params.Get(k).Export())315 if err != nil {316 return nil, fmt.Errorf("invalid timeout value: %w", err)317 }318 result.Timeout = t319 case "throw":320 result.Throw = params.Get(k).ToBoolean()321 case "responseType":322 responseType, err := httpext.ResponseTypeString(params.Get(k).String())323 if err != nil {324 return nil, err325 }326 result.ResponseType = responseType327 case "responseCallback":328 v := params.Get(k).Export()329 if v == nil {330 result.ResponseCallback = nil331 } else if c, ok := v.(*expectedStatuses); ok {332 result.ResponseCallback = c.match333 } else {334 return nil, fmt.Errorf("unsupported responseCallback")335 }336 }337 }338 }339 if result.ActiveJar != nil {340 httpext.SetRequestCookies(result.Req, result.ActiveJar, result.Cookies)341 }342 return result, nil343}344func (c *Client) prepareBatchArray(requests []interface{}) (345 []httpext.BatchParsedHTTPRequest, []*Response, error,346) {347 reqCount := len(requests)348 batchReqs := make([]httpext.BatchParsedHTTPRequest, reqCount)349 results := make([]*Response, reqCount)350 for i, req := range requests {351 resp := httpext.NewResponse()352 parsedReq, err := c.parseBatchRequest(i, req)353 if err != nil {354 resp.Error = err.Error()355 var k6e httpext.K6Error356 if errors.As(err, &k6e) {357 resp.ErrorCode = int(k6e.Code)358 }359 results[i] = c.responseFromHTTPext(resp)360 return batchReqs, results, err361 }362 batchReqs[i] = httpext.BatchParsedHTTPRequest{363 ParsedHTTPRequest: parsedReq,364 Response: resp,365 }366 results[i] = c.responseFromHTTPext(resp)367 }368 return batchReqs, results, nil369}370func (c *Client) prepareBatchObject(requests map[string]interface{}) (371 []httpext.BatchParsedHTTPRequest, map[string]*Response, error,372) {373 reqCount := len(requests)374 batchReqs := make([]httpext.BatchParsedHTTPRequest, reqCount)375 results := make(map[string]*Response, reqCount)376 i := 0377 for key, req := range requests {378 resp := httpext.NewResponse()379 parsedReq, err := c.parseBatchRequest(key, req)380 if err != nil {381 resp.Error = err.Error()382 var k6e httpext.K6Error383 if errors.As(err, &k6e) {384 resp.ErrorCode = int(k6e.Code)385 }386 results[key] = c.responseFromHTTPext(resp)387 return batchReqs, results, err388 }389 batchReqs[i] = httpext.BatchParsedHTTPRequest{390 ParsedHTTPRequest: parsedReq,391 Response: resp,392 }...

Full Screen

Full Screen

remote_write.go

Source:remote_write.go Github

copy

Full Screen

...132}133func (c *Client) StoreGenerated(total_series, batches, batch_size, batch int64) (httpext.Response, error) {134 ts, err := generate_series(total_series, batches, batch_size, batch)135 if err != nil {136 return *httpext.NewResponse(), err137 }138 return c.Store(ts)139}140func generate_series(total_series, batches, batch_size, batch int64) ([]Timeseries, error) {141 if total_series == 0 {142 return nil, nil143 }144 if batch > batches {145 return nil, errors.New("batch must be in the range of batches")146 }147 if total_series/batches != batch_size {148 return nil, errors.New("total_series must divide evenly into batches of size batch_size")149 }150 r := rand.New(rand.NewSource(time.Now().Unix()))151 series := make([]Timeseries, batch_size)152 timestamp := time.Now().UnixNano() / int64(time.Millisecond)153 for i := int64(0); i < batch_size; i++ {154 series_id := batch_size*(batch-1) + i155 labels := generate_cardinality_labels(total_series, series_id)156 labels = append(labels, Label{157 Name: "__name__",158 Value: "k6_generated_metric_" + strconv.Itoa(int(series_id)),159 })160 // Required for querying in order to have unique series excluding the metric name.161 labels = append(labels, Label{162 Name: "series_id",163 Value: strconv.Itoa(int(series_id)),164 })165 series[i] = Timeseries{166 labels,167 []Sample{{r.Float64() * 100, timestamp}},168 }169 }170 return series, nil171}172func generate_cardinality_labels(total_series, series_id int64) []Label {173 // exp is the greatest exponent of 10 that is less than total series.174 exp := int64(math.Log10(float64(total_series)))175 labels := make([]Label, 0, exp)176 for x := 1; int64(x) <= exp; x++ {177 labels = append(labels, Label{178 Name: "cardinality_1e" + strconv.Itoa(x),179 Value: strconv.Itoa(int(series_id / int64(math.Pow(10, float64(x))))),180 })181 }182 return labels183}184func (c *Client) Store(ts []Timeseries) (httpext.Response, error) {185 var batch []prompb.TimeSeries186 for _, t := range ts {187 batch = append(batch, FromTimeseriesToPrometheusTimeseries(t))188 }189 return c.store(batch)190}191func (c *Client) store(batch []prompb.TimeSeries) (httpext.Response, error) {192 // Required for k6 metrics193 state := c.vu.State()194 if state == nil {195 return *httpext.NewResponse(), errors.New("State is nil")196 }197 req := prompb.WriteRequest{198 Timeseries: batch,199 }200 data, err := proto.Marshal(&req)201 if err != nil {202 return *httpext.NewResponse(), errors.Wrap(err, "failed to marshal remote-write request")203 }204 compressed := snappy.Encode(nil, data)205 res, err := c.send(state, compressed)206 if err != nil {207 return *httpext.NewResponse(), errors.Wrap(err, "remote-write request failed")208 }209 res.Request.Body = ""210 return res, nil211}212// send sends a batch of samples to the HTTP endpoint, the request is the proto marshalled213// and encoded bytes214func (c *Client) send(state *lib.State, req []byte) (httpext.Response, error) {215 httpResp := httpext.NewResponse()216 r, err := http.NewRequest("POST", c.cfg.Url, nil)217 if err != nil {218 return *httpResp, err219 }220 r.Header.Add("Content-Encoding", "snappy")221 r.Header.Set("Content-Type", "application/x-protobuf")222 r.Header.Set("User-Agent", c.cfg.UserAgent)223 r.Header.Set("X-Prometheus-Remote-Write-Version", "0.0.2")224 if c.cfg.TenantName != "" {225 r.Header.Set("X-Scope-OrgID", c.cfg.TenantName)226 }227 duration, err := str2duration.ParseDuration(c.cfg.Timeout)228 if err != nil {229 return *httpResp, err230 }231 u, err := url.Parse(c.cfg.Url)232 if err != nil {233 return *httpResp, err234 }235 url, _ := httpext.NewURL(c.cfg.Url, u.Host+u.Path)236 response, err := httpext.MakeRequest(c.vu.Context(), state, &httpext.ParsedHTTPRequest{237 URL: &url,238 Req: r,239 Body: bytes.NewBuffer(req),240 Throw: state.Options.Throw.Bool,241 Redirects: state.Options.MaxRedirects,242 Timeout: duration,243 ResponseCallback: ResponseCallback,244 })245 if err != nil {246 return *httpResp, err247 }248 return *response, err249}250func ResponseCallback(n int) bool {251 return n == 200252}253func FromTimeseriesToPrometheusTimeseries(ts Timeseries) prompb.TimeSeries {254 var labels []prompb.Label255 var samples []prompb.Sample256 for _, label := range ts.Labels {257 labels = append(labels, prompb.Label{258 Name: label.Name,259 Value: label.Value,260 })261 }262 for _, sample := range ts.Samples {263 if sample.Timestamp == 0 {264 sample.Timestamp = time.Now().UnixNano() / int64(time.Millisecond)265 }266 samples = append(samples, prompb.Sample{267 Value: sample.Value,268 Timestamp: sample.Timestamp,269 })270 }271 return prompb.TimeSeries{272 Labels: labels,273 Samples: samples,274 }275}276// The only supported things are:277// 1. replacing ${series_id} with the series_id provided278// 2. replacing ${series_id/<integer>} with the evaluation of that279// 3. if error in parsing return error280func compileTemplate(template string) (*labelGenerator, error) {281 i := strings.Index(template, "${series_id")282 if i == -1 {283 return newIdentityLabelGenerator(template), nil284 }285 switch template[i+len("${series_id")] {286 case '}':287 return &labelGenerator{288 AppendByte: func(b []byte, seriesID int) []byte {289 b = append(b, template[:i]...)290 b = strconv.AppendInt(b, int64(seriesID), 10)291 return append(b, template[i+len("${series_id}"):]...)292 },293 }, nil294 case '%':295 end := strings.Index(template[i:], "}")296 if end == -1 {297 return nil, errors.New("no closing bracket in template")298 }299 d, err := strconv.Atoi(template[i+len("${series_id%") : i+end])300 if err != nil {301 return nil, fmt.Errorf("can't parse divisor of the module operator %w", err)302 }303 possibleValues := make([][]byte, d)304 // TODO have an upper limit305 for j := 0; j < d; j++ {306 var b []byte307 b = append(b, template[:i]...)308 b = strconv.AppendInt(b, int64(j), 10)309 possibleValues[j] = append(b, template[i+end+1:]...)310 }311 return &labelGenerator{312 AppendByte: func(b []byte, seriesID int) []byte {313 return append(b, possibleValues[seriesID%d]...)314 },315 }, nil316 case '/':317 end := strings.Index(template[i:], "}")318 if end == -1 {319 return nil, errors.New("no closing bracket in template")320 }321 d, err := strconv.Atoi(template[i+len("${series_id/") : i+end])322 if err != nil {323 return nil, err324 }325 var memoize []byte326 var memoizeValue int64327 return &labelGenerator{328 AppendByte: func(b []byte, seriesID int) []byte {329 value := int64(seriesID / d)330 if memoize == nil || value != memoizeValue {331 memoizeValue = value332 memoize = memoize[:0]333 memoize = append(memoize, template[:i]...)334 memoize = strconv.AppendInt(memoize, value, 10)335 memoize = append(memoize, template[i+end+1:]...)336 }337 return append(b, memoize...)338 },339 }, nil340 }341 return nil, errors.New("unsupported template")342}343type labelGenerator struct {344 AppendByte func([]byte, int) []byte345}346func newIdentityLabelGenerator(t string) *labelGenerator {347 return &labelGenerator{348 AppendByte: func(b []byte, _ int) []byte { return append(b, t...) },349 }350}351// this is opaque on purpose so that it can't be done anything to from the js side352type labelTemplates struct {353 compiledTemplates []compiledTemplate354 labelValue []byte355}356type compiledTemplate struct {357 name string358 generator *labelGenerator359}360func compileLabelTemplates(labelsTemplate map[string]string) (*labelTemplates, error) {361 compiledTemplates := make([]compiledTemplate, len(labelsTemplate))362 {363 i := 0364 var err error365 for k, v := range labelsTemplate {366 compiledTemplates[i].name = k367 compiledTemplates[i].generator, err = compileTemplate(v)368 if err != nil {369 return nil, fmt.Errorf("error while compiling template %q, %w", v, err)370 }371 i++372 }373 }374 sort.Slice(compiledTemplates, func(i, j int) bool {375 return compiledTemplates[i].name < compiledTemplates[j].name376 })377 return &labelTemplates{378 compiledTemplates: compiledTemplates,379 labelValue: make([]byte, 128), // this is way more than necessary and it will grow if needed380 }, nil381}382func (c *Client) StoreFromTemplates(383 minValue, maxValue int,384 timestamp int64, minSeriesID, maxSeriesID int,385 labelsTemplate map[string]string,386) (httpext.Response, error) {387 template, err := compileLabelTemplates(labelsTemplate)388 if err != nil {389 return *httpext.NewResponse(), err390 }391 return c.StoreFromPrecompiledTemplates(minValue, maxValue, timestamp, minSeriesID, maxSeriesID, template)392}393func (template *labelTemplates) writeFor(w *bytes.Buffer, value float64, seriesID int, timestamp int64) (err error) {394 labelValue := template.labelValue[:]395 for _, template := range template.compiledTemplates {396 labelValue = labelValue[:0]397 w.WriteByte(0xa)398 labelValue = protowire.AppendVarint(labelValue, uint64(len(template.name)))399 n1 := len(labelValue)400 labelValue = template.generator.AppendByte(labelValue, seriesID)401 n2 := len(labelValue)402 labelValue = protowire.AppendVarint(labelValue, uint64(n2-n1))403 n3 := len(labelValue)404 labelValue = protowire.AppendVarint(labelValue, uint64(n3+1+1+len(template.name)))405 w.Write(labelValue[n3:])406 w.WriteByte(0xa)407 w.Write(labelValue[:n1])408 w.WriteString(template.name)409 w.WriteByte(0x12)410 w.Write(labelValue[n2:n3])411 w.Write(labelValue[n1:n2])412 }413 labelValue = labelValue[:10]414 labelValue[0] = 0x9415 binary.LittleEndian.PutUint64(labelValue[1:9], uint64(math.Float64bits(value)))416 labelValue[9] = 0x10417 labelValue = protowire.AppendVarint(labelValue, uint64(timestamp))418 n := len(labelValue)419 labelValue = labelValue[:n+1]420 labelValue[n] = 0x12421 labelValue = protowire.AppendVarint(labelValue, uint64(n))422 w.Write(labelValue[n:])423 w.Write(labelValue[:n])424 template.labelValue = labelValue425 return nil // TODO fix426}427func (c *Client) StoreFromPrecompiledTemplates(428 minValue, maxValue int,429 timestamp int64, minSeriesID, maxSeriesID int,430 template *labelTemplates,431) (httpext.Response, error) {432 state := c.vu.State()433 if state == nil {434 return *httpext.NewResponse(), errors.New("State is nil")435 }436 r := rand.New(rand.NewSource(time.Now().Unix()))437 buf := generateFromPrecompiledTemplates(r, minValue, maxValue, timestamp, minSeriesID, maxSeriesID, template)438 b := buf.Bytes()439 compressed := make([]byte, len(b)/9) // the general size is actually between 1/9 and 1/10th but this is closed enough440 compressed = snappy.Encode(compressed, b)441 res, err := c.send(state, compressed)442 if err != nil {443 return *httpext.NewResponse(), errors.Wrap(err, "remote-write request failed")444 }445 res.Request.Body = ""446 return res, nil447}448func generateFromPrecompiledTemplates(449 r *rand.Rand,450 minValue, maxValue int,451 timestamp int64, minSeriesID, maxSeriesID int,452 template *labelTemplates,453) *bytes.Buffer {454 bigB := make([]byte, 1024)455 buf := new(bytes.Buffer)456 buf.Reset()457 tsBuf := new(bytes.Buffer)...

Full Screen

Full Screen

client.go

Source:client.go Github

copy

Full Screen

...149}150func (c *Client) sendQuery(q *Query) (httpext.Response, error) {151 state := c.vu.State()152 if state == nil {153 return *httpext.NewResponse(), errors.New("state is nil")154 }155 httpResp := httpext.NewResponse()156 path := q.Endpoint()157 urlString, err := buildURL(c.cfg.URL.String(), path, q.Values().Encode())158 if err != nil {159 return *httpext.NewResponse(), err160 }161 r, err := http.NewRequest(http.MethodGet, urlString, nil)162 if err != nil {163 return *httpResp, err164 }165 r.Header.Set("User-Agent", c.cfg.UserAgent)166 r.Header.Set("Accept", ContentTypeJSON)167 if c.cfg.TenantID != "" {168 r.Header.Set("X-Scope-OrgID", c.cfg.TenantID)169 } else {170 r.Header.Set("X-Scope-OrgID", fmt.Sprintf("%s-%d", TenantPrefix, state.VUID))171 }172 url, _ := httpext.NewURL(urlString, path)173 response, err := httpext.MakeRequest(c.vu.Context(), state, &httpext.ParsedHTTPRequest{174 URL: &url,175 Req: r,176 Throw: state.Options.Throw.Bool,177 Redirects: state.Options.MaxRedirects,178 Timeout: c.cfg.Timeout,179 ResponseCallback: IsSuccessfulResponse,180 })181 if err != nil {182 return *httpResp, err183 }184 return *response, err185}186func (c *Client) Push() (httpext.Response, error) {187 // 5 streams per batch188 // batch size between 800KB and 1MB189 return c.PushParameterized(5, 800*1024, 1024*1024)190}191// PushParametrized is deprecated in favor or PushParameterized192func (c *Client) PushParametrized(streams, minBatchSize, maxBatchSize int) (httpext.Response, error) {193 if state := c.vu.State(); state == nil {194 return *httpext.NewResponse(), errors.New("state is nil")195 } else {196 state.Logger.Warn("method pushParametrized() is deprecated and will be removed in future releases; please use pushParameterized() instead")197 }198 return c.PushParameterized(streams, minBatchSize, maxBatchSize)199}200func (c *Client) PushParameterized(streams, minBatchSize, maxBatchSize int) (httpext.Response, error) {201 state := c.vu.State()202 if state == nil {203 return *httpext.NewResponse(), errors.New("state is nil")204 }205 batch := c.newBatch(c.cfg.Labels, streams, minBatchSize, maxBatchSize)206 return c.pushBatch(batch)207}208func (c *Client) pushBatch(batch *Batch) (httpext.Response, error) {209 state := c.vu.State()210 if state == nil {211 return *httpext.NewResponse(), errors.New("state is nil")212 }213 var buf []byte214 var err error215 // Use snappy encoded Protobuf for 90% of the requests216 // Use JSON encoding for 10% of the requests217 encodeSnappy := rand.Float64() < c.cfg.ProtobufRatio218 if encodeSnappy {219 buf, _, err = batch.encodeSnappy()220 } else {221 buf, _, err = batch.encodeJSON()222 }223 if err != nil {224 return *httpext.NewResponse(), errors.Wrap(err, "failed to encode payload")225 }226 res, err := c.send(state, buf, encodeSnappy)227 if err != nil {228 return *httpext.NewResponse(), errors.Wrap(err, "push request failed")229 }230 res.Request.Body = ""231 return res, nil232}233func (c *Client) send(state *lib.State, buf []byte, useProtobuf bool) (httpext.Response, error) {234 httpResp := httpext.NewResponse()235 path := "/loki/api/v1/push"236 r, err := http.NewRequest(http.MethodPost, c.cfg.URL.String()+path, nil)237 if err != nil {238 return *httpResp, err239 }240 r.Header.Set("User-Agent", c.cfg.UserAgent)241 r.Header.Set("Accept", ContentTypeJSON)242 if c.cfg.TenantID != "" {243 r.Header.Set("X-Scope-OrgID", c.cfg.TenantID)244 } else {245 r.Header.Set("X-Scope-OrgID", fmt.Sprintf("%s-%d", TenantPrefix, state.VUID))246 }247 if useProtobuf {248 r.Header.Set("Content-Type", ContentTypeProtobuf)...

Full Screen

Full Screen

NewResponse

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 rr := httptest.NewRecorder()7 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {8 fmt.Fprint(w, "Hello, World!")9 })10 handler.ServeHTTP(rr, req)11 if status := rr.Code; status != http.StatusOK {12 fmt.Println(status)13 }14 if rr.Body.String() != expected {15 fmt.Println(rr.Body.String())16 }17}18import (19func main() {20 if err != nil {21 fmt.Println(err)22 }23 rr := httptest.NewRecorder()24 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {25 fmt.Fprint(w, "Hello, World!")26 })27 handler.ServeHTTP(rr, req)28 if status := rr.Code; status != http.StatusOK {29 fmt.Println(status)30 }31 if rr.Body.String() != expected {32 fmt.Println(rr.Body.String())33 }34}

Full Screen

Full Screen

NewResponse

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 rr := httptest.NewRecorder()7 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {8 w.Write([]byte("Hello World!"))9 })10 handler.ServeHTTP(rr, req)11 if status := rr.Code; status != http.StatusOK {12 fmt.Println("Error: status code is not OK")13 }14 if rr.Body.String() != expected {15 fmt.Println("Error: response body is not correct")

Full Screen

Full Screen

NewResponse

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 resp := httpext.NewResponse(http.StatusOK, "Hello World")4 fmt.Println(resp)5}6&{200 OK 0 [] false 0 map[] 0xc0000c6000 <nil> <nil> map[] 0 [] false}

Full Screen

Full Screen

NewResponse

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 response := httpext.NewResponse()4 response.SetStatusCode(200)5 response.SetContentType("text/html")6 response.SetBody("Hello World!")7 response.WriteResponse()8}9import (10func main() {11 request := httpext.NewRequest()12 request.SetMethod("GET")13 request.SetHeaders(map[string]string{14 })15 request.SetBody("Hello World!")16 request.SetTimeout(10)17 response, err := request.Send()18 if err != nil {19 fmt.Println(err)20 }21 fmt.Println(response.GetStatusCode())22 fmt.Println(response.GetContentType())23 fmt.Println(response.GetBody())24}25import (26func main() {27 if err != nil {28 fmt.Println(err)29 }30 fmt.Println(response.GetStatusCode())31 fmt.Println(response.GetContentType())32 fmt.Println(response.GetBody())33 }, "Hello World!")34 if err != nil {35 fmt.Println(err)36 }37 fmt.Println(response.GetStatusCode())38 fmt.Println(response.GetContentType())39 fmt.Println(response.GetBody())

Full Screen

Full Screen

NewResponse

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 resp := httpext.NewResponse(200, "Success")5 fmt.Println(resp)6}7import (8func main() {9 fmt.Println("Hello, playground")10 resp := httpext.NewResponse(200, "Success")11 fmt.Println(resp)12}13import (14func main() {15 fmt.Println("Hello, playground")16 resp := httpext.NewResponse(200, "Success")17 fmt.Println(resp)18}19import (20func main() {21 fmt.Println("Hello, playground")22 resp := httpext.NewResponse(200, "Success")23 fmt.Println(resp)24}25import (26func main() {27 fmt.Println("Hello, playground")28 resp := httpext.NewResponse(200, "Success")29 fmt.Println(resp)30}31import (32func main() {33 fmt.Println("Hello, playground")34 resp := httpext.NewResponse(200, "Success")35 fmt.Println(resp)36}37import (38func main() {39 fmt.Println("Hello, playground")40 resp := httpext.NewResponse(200, "Success")41 fmt.Println(resp)42}43import (44func main() {45 fmt.Println("Hello, playground")46 resp := httpext.NewResponse(200, "Success")47 fmt.Println(resp)48}49import (50func main() {

Full Screen

Full Screen

NewResponse

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 res := httpext.NewResponse(http.StatusOK, "Hello World")4 fmt.Println(res)5}6import (7func main() {8 fmt.Println(req)9}10import (11func main() {12 res := httpext.NewResponse(http.StatusOK, "Hello World")13 fmt.Println(res.Write())14}15import (16func main() {17 res := httpext.NewResponse(http.StatusOK, "Hello World")18 fmt.Println(res.WriteJSON())19}20import (21func main() {22 res := httpext.NewResponse(http.StatusOK, "Hello World")23 fmt.Println(res.WriteXML())24}25import (26func main() {27 res := httpext.NewResponse(http.StatusOK, "Hello World")28 fmt.Println(res.WriteYAML())29}30import (31func main() {32 res := httpext.NewResponse(http.StatusOK, "Hello World")33 fmt.Println(res.WriteBytes())34}35import (36func main() {37 res := httpext.NewResponse(http.StatusOK

Full Screen

Full Screen

NewResponse

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 res := httpext.NewResponse(http.StatusOK, "Hello World")4 fmt.Println(res)5}6import (7func NewResponse(statusCode int, body string) *http.Response {8 return &http.Response{9 Body: nopCloser{fmt.Sprint(body)},10 }11}12type nopCloser struct {13}14func (nopCloser) Close() error { return nil }

Full Screen

Full Screen

NewResponse

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 resp := httpext.NewResponse(http.StatusOK, "Hello, playground")5 fmt.Println(resp)6}7import (8func main() {9 fmt.Println("Hello, playground")10 resp := httpext.NewResponseWithHeaders(http.StatusOK, "Hello, playground", map[string]string{"Content-Type": "text/plain"})11 fmt.Println(resp)12}13import (14func main() {15 fmt.Println("Hello, playground")16 resp := httpext.NewResponseWithHeaders(http.StatusOK, "Hello, playground", nil)17 fmt.Println(resp)18}

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run K6 automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful