k6 icon indicating copy to clipboard operation
k6 copied to clipboard

Request modification

Open TheAsda opened this issue 3 years ago • 2 comments

Feature Description

We have specific authentication flow that requires to attach custom header to every request. I wrote extension that can generate header but attaching it to request is manual process. Sample:

import http from 'k6/http';
import auth from 'k6/x/auth';

export function setup() {
  auth.setup();
}

export default function () {
  const header = auth.getHeader();
  http.get('<some url>', {
    headers: {
      Auth: header,
    },
  });
}

Header has to be generated for every request so i cannot initialize it once in setup. It would be great to be able to somehow modify request before execution.

Suggested Solution (optional)

I see a couple of options here:

  1. Add ability to attach some function for modification request like
import http from 'k6/http';
import auth from 'k6/x/auth';

http.applyMiddleware((req) => {
  req.headers.Auth = auth.getHeader();
  return req;
});
  1. Add ability to affect on RoundTripper on Go level:
func init() {
	custom := Custom{
		original: ctx.Transport,
	}
	ctx.Transport = custom
}

type Custom struct {
	original http.RoundTripper
}

func (c Custom) RoundTrip(req *http.Request) (*http.Response, error) {
	header := getHeader()
	req.Header.Add("Auth", header)
	return c.original.RoundTrip(req)
}

// or

func init() {
	modules.AddRoundTripper(func(original http.RoundTripper) http.RoundTripper {
		return Custom{
			original: original,
		}
	})
}

Personally i'd prefer second option as it can give more flexibility.

TheAsda avatar Aug 26 '22 19:08 TheAsda

Another option might be registration of custom auth method like

modules.RegisterAuth("custom", func(req *http.Request) *http.Request {
	//...
})
http.get('<some url>', { auth: 'custom' });

TheAsda avatar Aug 26 '22 19:08 TheAsda

Thanks for opening this issue and sorry for the slow reply! It's a known problem that was previously mentioned in https://github.com/grafana/k6/issues/761 (and probably in other new-http issues) that we'd like to address with a new k6 HTTP API soon (https://github.com/grafana/k6/issues/2461).

For now, the httpx JavaScript library that we host on jslib.k6.io might be sufficient for your needs. It's a wrapper around the existing k6/http API, take a look:

  • https://k6.io/docs/javascript-api/jslib/httpx
  • https://github.com/grafana/k6-jslib-httpx

na-- avatar Sep 08 '22 06:09 na--

This won't be implemented in the current HTTP API, and since there's a workaround with the httpx library, I'll close this issue.

Request modification is a feature we'd like to have in the new HTTP API (initial design document), which we're starting to work on now. We're still ironing out the design and syntax, so feel free to follow the issue and document for details.

imiric avatar Mar 28 '23 14:03 imiric