package actions import ( "bytes" "fmt" "io" "net/http" "slices" "strings" . "github.com/mickael-kerjean/filestash/server/common" ) func init() { Hooks.Register.WorkflowAction(&RunApi{}) } type RunApi struct{} func (this *RunApi) Manifest() WorkflowSpecs { return WorkflowSpecs{ Name: "run/api", Title: "Make API Call", Icon: ``, Specs: map[string]FormElement{ "url": { Type: "text", }, "method": { Type: "select", Opts: []string{"POST", "PUT", "GET", "PATCH"}, }, "headers": { Type: "long_text", }, "body": { Type: "long_text", }, }, } } func (this *RunApi) Execute(params map[string]string, input map[string]string) (map[string]string, error) { req, err := http.NewRequest(params["method"], params["url"], bytes.NewBufferString(params["body"])) if err != nil { return input, err } else if params["headers"] != "" { for _, header := range strings.Split(params["headers"], "\n") { if parts := strings.SplitN(strings.TrimSpace(header), ":", 2); len(parts) == 2 { req.Header.Add( strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1]), ) } } } if params["body"] != "" && slices.Contains([]string{"POST", "PUT", "PATCH"}, params["method"]) && req.Header.Get("Content-Type") == "" { req.Header.Set("Content-Type", "application/json") } resp, err := HTTP.Do(req) if err != nil { return input, err } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { return input, NewError(fmt.Sprintf("received status code is %d", resp.StatusCode), resp.StatusCode) } responseBody, err := io.ReadAll(resp.Body) if err != nil { return input, err } output := make(map[string]string) for k, v := range input { output[k] = v } output["http::status"] = string(resp.StatusCode) output["http::response"] = string(responseBody) return output, nil }