MCPcopy
hub / github.com/grafana/k6 / NewModuleInstance

Method NewModuleInstance

js/modules/k6/http/http.go:40–121  ·  view source on GitHub ↗

NewModuleInstance returns an HTTP module instance for each VU.

(vu modules.VU)

Source from the content-addressed store, hash-verified

38
39// NewModuleInstance returns an HTTP module instance for each VU.
40func (r *RootModule) NewModuleInstance(vu modules.VU) modules.Instance {
41 rt := vu.Runtime()
42 mi := &ModuleInstance{
43 vu: vu,
44 rootModule: r,
45 exports: rt.NewObject(),
46 }
47 mi.defineConstants()
48
49 mi.defaultClient = &Client{
50 // TODO: configure this from lib.Options and get rid of some of the
51 // things in the VU State struct that should be here. See
52 // https://github.com/grafana/k6/issues/2293
53 moduleInstance: mi,
54 responseCallback: defaultExpectedStatuses.match,
55 }
56
57 mustExport := func(name string, value any) {
58 if err := mi.exports.Set(name, value); err != nil {
59 common.Throw(rt, err)
60 }
61 }
62
63 mustExport("url", mi.URL)
64 mustExport("CookieJar", mi.newCookieJar)
65 mustExport("cookieJar", mi.getVUCookieJar)
66 mustExport("file", mi.file) // TODO: deprecate or refactor?
67
68 // TODO: refactor so the Client actually has better APIs and these are
69 // wrappers (facades) that convert the old k6 idiosyncratic APIs to the new
70 // proper Client ones that accept Request objects and don't suck
71 mustExport("get", func(url sobek.Value, args ...sobek.Value) (*Response, error) {
72 // http.get should not have more than one additional argument
73 if len(args) > 1 {
74 if state := mi.vu.State(); state != nil {
75 state.Logger.Warnf(
76 "http.get only accepts a url and a params argument (2 arguments), but %d were given",
77 len(args)+1,
78 )
79 }
80 }
81 // http.get(url, params) doesn't have a body argument, so we add undefined
82 // as the third argument to http.request(method, url, body, params)
83 args = append([]sobek.Value{sobek.Undefined()}, args...)
84 return mi.defaultClient.Request(http.MethodGet, url, args...)
85 })
86 mustExport("head", func(url sobek.Value, args ...sobek.Value) (*Response, error) {
87 // http.head should not have more than one additional argument
88 if len(args) > 1 {
89 if state := mi.vu.State(); state != nil {
90 state.Logger.Warnf(
91 "http.head only accepts a url and a params argument (2 arguments), but %d were given",
92 len(args)+1,
93 )
94 }
95 }
96 // http.head(url, params) doesn't have a body argument, so we add undefined
97 // as the third argument to http.request(method, url, body, params)

Callers

nothing calls this directly

Calls 8

defineConstantsMethod · 0.95
ThrowFunction · 0.92
WarnfMethod · 0.80
getMethodClosureMethod · 0.80
RuntimeMethod · 0.65
StateMethod · 0.65
RequestMethod · 0.65
SetMethod · 0.45

Tested by

no test coverage detected