util.HttpRequest helper to make requests with headers (#2678)

This commit is contained in:
Alan Hamlett 2023-01-30 10:29:06 +01:00 committed by GitHub
parent f7677549ea
commit 0500cc234d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 16 additions and 0 deletions

View File

@ -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)

View File

@ -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)
}

View File

@ -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