From 0500cc234df3ed9ddec6b727f96e9e5e40f62c1a Mon Sep 17 00:00:00 2001 From: Alan Hamlett Date: Mon, 30 Jan 2023 10:29:06 +0100 Subject: [PATCH] util.HttpRequest helper to make requests with headers (#2678) --- cmd/micro/initlua.go | 1 + internal/util/util.go | 14 ++++++++++++++ runtime/help/plugins.md | 1 + 3 files changed, 16 insertions(+) diff --git a/cmd/micro/initlua.go b/cmd/micro/initlua.go index dcb60830..3cbb3b2d 100644 --- a/cmd/micro/initlua.go +++ b/cmd/micro/initlua.go @@ -150,6 +150,7 @@ func luaImportMicroUtil() *lua.LTable { ulua.L.SetField(pkg, "Unzip", luar.New(ulua.L, util.Unzip)) ulua.L.SetField(pkg, "Version", luar.New(ulua.L, util.Version)) ulua.L.SetField(pkg, "SemVersion", luar.New(ulua.L, util.SemVersion)) + ulua.L.SetField(pkg, "HttpRequest", luar.New(ulua.L, util.HttpRequest)) ulua.L.SetField(pkg, "CharacterCountInString", luar.New(ulua.L, util.CharacterCountInString)) ulua.L.SetField(pkg, "RuneStr", luar.New(ulua.L, func(r rune) string { return string(r) diff --git a/internal/util/util.go b/internal/util/util.go index 6580145c..81448f0d 100644 --- a/internal/util/util.go +++ b/internal/util/util.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "io" + "net/http" "os" "os/user" "path/filepath" @@ -493,3 +494,16 @@ func Unzip(src, dest string) error { return nil } + +// HttpRequest returns a new http.Client for making custom requests (for lua plugins) +func HttpRequest(method string, url string, headers []string) (resp *http.Response, err error) { + client := http.Client{} + req, err := http.NewRequest(method, url, nil) + if err != nil { + return nil, err + } + for i := 0; i < len(headers); i += 2 { + req.Header.Add(headers[i], headers[i+1]) + } + return client.Do(req) +} diff --git a/runtime/help/plugins.md b/runtime/help/plugins.md index c2e202ac..a175f3e8 100644 --- a/runtime/help/plugins.md +++ b/runtime/help/plugins.md @@ -287,6 +287,7 @@ The packages and functions are listed below (in Go type signatures): - `String(b []byte) string`: converts a byte array to a string. - `RuneStr(r rune) string`: converts a rune to a string. - `Unzip(src, dest string) error`: unzips a file to given folder. + - `HttpRequest(method string, url string, headers []string) (http.Response, error)`: makes a http request. This may seem like a small list of available functions but some of the objects returned by the functions have many methods. The Lua plugin may access any