Skip to content

Commit

Permalink
feat(sys.http.post): add option to include response in output
Browse files Browse the repository at this point in the history
Added a new parameter `includeResponse` to the SysHTTPPost function to allow inclusion of the HTTP POST response in the output. This provides more flexibility in handling responses directly within the tool.
  • Loading branch information
rinor committed Sep 20, 2024
1 parent 8ecad90 commit 3e3e750
Showing 1 changed file with 28 additions and 5 deletions.
33 changes: 28 additions & 5 deletions pkg/builtin/builtin.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"time"

Expand Down Expand Up @@ -137,7 +138,8 @@ var tools = map[string]types.Tool{
Arguments: types.ObjectSchema(
"url", "The URL to POST to",
"content", "The content to POST",
"contentType", "The \"content type\" of the content such as application/json or text/plain"),
"contentType", "The \"content type\" of the content such as application/json or text/plain",
"includeResponse", "true/false, include POST response to output. Default false"),
},
BuiltinFunc: SysHTTPPost,
},
Expand Down Expand Up @@ -622,14 +624,16 @@ func SysHTTPHtml2Text(ctx context.Context, env []string, input string, progress

func SysHTTPPost(ctx context.Context, _ []string, input string, _ chan<- string) (_ string, err error) {
var params struct {
URL string `json:"url,omitempty"`
Content string `json:"content,omitempty"`
ContentType string `json:"contentType,omitempty"`
URL string `json:"url,omitempty"`
Content string `json:"content,omitempty"`
ContentType string `json:"contentType,omitempty"`
IncludeResponse string `json:"includeResponse,omitempty"`
}
if err := json.Unmarshal([]byte(input), &params); err != nil {
return invalidArgument(input, err), nil
}

includeResponse, _ := strconv.ParseBool(params.IncludeResponse)
params.URL = fixQueries(params.URL)

req, err := http.NewRequestWithContext(ctx, http.MethodPost, params.URL, strings.NewReader(params.Content))
Expand All @@ -648,11 +652,30 @@ func SysHTTPPost(ctx context.Context, _ []string, input string, _ chan<- string)
}
defer resp.Body.Close()

_, _ = io.ReadAll(resp.Body)
var (
rawData []byte
outputData string
)

rawData, err = io.ReadAll(resp.Body)
if includeResponse && err != nil {
rawData = []byte(err.Error())
}
if includeResponse {
outputData = strings.TrimSpace(string(rawData))
}

if resp.StatusCode > 399 {
if includeResponse && len(outputData) > 0 {
return fmt.Sprintf("Failed to post URL %s: %s (cause: %s)", params.URL, resp.Status, outputData), nil
}
return fmt.Sprintf("Failed to post URL %s: %s", params.URL, resp.Status), nil
}

if includeResponse && len(outputData) > 0 {
return outputData, nil
}

return fmt.Sprintf("Wrote %d to %s", len([]byte(params.Content)), params.URL), nil
}

Expand Down

0 comments on commit 3e3e750

Please sign in to comment.