Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't use url.Values with escaped strings that contain string formatter placeholders #17

Open
ChrisSchinnerl opened this issue Dec 8, 2023 · 0 comments

Comments

@ChrisSchinnerl
Copy link
Member

Right now when trying to use url.Values with jape, the only way to do so without making the analyser angry is like this:

func (c *Client) PruneMetrics(ctx context.Context, metric string, cutoff time.Time) error {
	values := url.Values{}
	values.Set("cutoff", api.TimeRFC3339(cutoff).String())
	return c.c.WithContext(ctx).DELETE(fmt.Sprintf("/metric/%s?" + values.Encode(), metric))
}

However, using + for concatenation only works if values.Encode doesn't produce a string with valid formatting placeholders which is unfortunately the case when passing a RFC3339 timestamp. Because then the server can't decode the string anymore since it will contain the string (MISSING). To fix the issue, you can do the following which is concatenating after formatting the string:

func (c *Client) PruneMetrics(ctx context.Context, metric string, cutoff time.Time) error {
	values := url.Values{}
	values.Set("cutoff", api.TimeRFC3339(cutoff).String())
	return c.c.WithContext(ctx).DELETE(fmt.Sprintf("/metric/%s?", metric) + values.Encode())
}

Or by doing

func (c *Client) PruneMetrics(ctx context.Context, metric string, cutoff time.Time) error {
	values := url.Values{}
	values.Set("cutoff", api.TimeRFC3339(cutoff).String())
	return c.c.WithContext(ctx).DELETE(fmt.Sprintf("/metric/%s?%s", metric, values.Encode())
}

Both fixes break the Analyser unfortunately. The only way I've gotten it to work was by doing this:

func (c *Client) PruneMetrics(ctx context.Context, metric string, cutoff time.Time) error {
	values := url.Values{}
	values.Set("cutoff", api.TimeRFC3339(cutoff).String())
	c.c.Custom("DELETE", fmt.Sprintf("/metric/%s?"+values.Encode(), metric), nil, nil)

	u, err := url.Parse(fmt.Sprintf("%s/metric/%s", c.c.BaseURL, metric))
	if err != nil {
		panic(err)
	}
	u.RawQuery = values.Encode()
	req, err := http.NewRequestWithContext(ctx, "DELETE", u.String(), nil)
	if err != nil {
		panic(err)
	}
	req.SetBasicAuth("", c.c.WithContext(ctx).Password)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		err, _ := io.ReadAll(resp.Body)
		return errors.New(string(err))
	}
	return nil
}

Which unfortunately is a lot more code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant