Repository: danielgtaylor/huma
Pull request #584 (2024-09-19 22:21:37)

fix: unsupported param type url.URL


<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit

- **New Features**
	- Enhanced the `Register` function to support and validate `url.URL` types, ensuring proper handling of URL inputs.
	- Added functionality to the test suite to handle URL parameters, improving robustness in testing URL validation.

- **Bug Fixes**
	- Improved error handling for invalid URL values, providing clearer feedback to users.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

coderabbitai[bot]: <!-- This is an auto-generated comment: summarize by coderabbit.ai -->
<!-- This is an auto-generated comment: summarize review in progress by coderabbit.ai -->

> [!NOTE]
> Currently processing new changes in this PR. This may take a few minutes, please wait...
> 
> 	<details>
> <summary>Commits</summary>
> 
> Files that changed from the base of the PR and between 69d32c3036d133606ad09c03ea1b27b2c980d82a and f8f175bc53ffa9b16b447679c663373c107ec4c4.
> 
> </details>
> 
> 
> <details>
> <summary>Files selected for processing (1)</summary>
> 
> * huma.go (2 hunks)
> 
> </details>
> 
> 	```ascii
>  ________________________________________________
> < Squeezing intelligence out of LLMs since 2023. >
>  ------------------------------------------------
>   \
>    \   (\__/)
>        (•ㅅ•)
>        / 　 づ
> ```

<!-- end of auto-generated comment: summarize review in progress by coderabbit.ai --><!-- usage_tips_start -->

> [!TIP]
> <details>
> <summary>CodeRabbit can approve the review once all CodeRabbit's comments are resolved.</summary>
> 
> Enable the `reviews.request_changes_workflow` setting in your project's settings in CodeRabbit to automatically approve the review once all CodeRabbit's comments are resolved.
> 
> </details>

<!-- usage_tips_end --><!-- tips_start -->

---

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

<details>
<summary>Share</summary>

- [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai)
- [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai)
- [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai)
- [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)

</details>

<details>
<summary>Tips</summary>

### Chat

There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai):

- Review comments: Directly reply to a review comment made by CodeRabbit. Example:
-- `I pushed a fix in commit <commit_id>, please review it.`
-- `Generate unit testing code for this file.`
	- `Open a follow-up GitHub issue for this discussion.`
- Files and specific lines of code (under the "Files changed" tab): Tag `@coderabbitai` in a new review comment at the desired location with your query. Examples:
-- `@coderabbitai generate unit testing code for this file.`
--	`@coderabbitai modularize this function.`
- PR comments: Tag `@coderabbitai` in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
-- `@coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.`
-- `@coderabbitai read src/utils.ts and generate unit testing code.`
-- `@coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.`
-- `@coderabbitai help me debug CodeRabbit configuration file.`

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

### CodeRabbit Commands (Invoked using PR comments)

- `@coderabbitai pause` to pause the reviews on a PR.
- `@coderabbitai resume` to resume the paused reviews.
- `@coderabbitai review` to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
- `@coderabbitai full review` to do a full review from scratch and review all the files again.
- `@coderabbitai summary` to regenerate the summary of the PR.
- `@coderabbitai resolve` resolve all the CodeRabbit review comments.
- `@coderabbitai configuration` to show the current CodeRabbit configuration for the repository.
- `@coderabbitai help` to get help.

### Other keywords and placeholders

- Add `@coderabbitai ignore` anywhere in the PR description to prevent this PR from being reviewed.
- Add `@coderabbitai summary` to generate the high-level summary at a specific location in the PR description.
- Add `@coderabbitai` anywhere in the PR title to generate the title automatically.

### CodeRabbit Configuration File (`.coderabbit.yaml`)

- You can programmatically configure CodeRabbit by adding a `.coderabbit.yaml` file to the root of your repository.
- Please see the [configuration documentation](https://docs.coderabbit.ai/guides/configure-coderabbit) for more information.
- If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: `# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json`

### Documentation and Community

- Visit our [Documentation](https://coderabbit.ai/docs) for detailed information on how to use CodeRabbit.
- Join our [Discord Community](https://discord.com/invite/GsXnASn26c) to get help, request features, and share feedback.
- Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.

</details>

<!-- tips_end -->
codecov[bot]: ## [Codecov](https://app.codecov.io/gh/danielgtaylor/huma/pull/584?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Daniel+G.+Taylor) Report
Attention: Patch coverage is `0%` with `8 lines` in your changes missing coverage. Please review.
> Project coverage is 92.59%. Comparing base [(`69d32c3`)](https://app.codecov.io/gh/danielgtaylor/huma/commit/69d32c3036d133606ad09c03ea1b27b2c980d82a?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Daniel+G.+Taylor) to head [(`f8f175b`)](https://app.codecov.io/gh/danielgtaylor/huma/commit/f8f175bc53ffa9b16b447679c663373c107ec4c4?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Daniel+G.+Taylor).

| [Files with missing lines](https://app.codecov.io/gh/danielgtaylor/huma/pull/584?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Daniel+G.+Taylor) | Patch % | Lines |
|---|---|---|
| [huma.go](https://app.codecov.io/gh/danielgtaylor/huma/pull/584?src=pr&el=tree&filepath=huma.go&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Daniel+G.+Taylor#diff-aHVtYS5nbw==) | 0.00% | [7 Missing and 1 partial :warning: ](https://app.codecov.io/gh/danielgtaylor/huma/pull/584?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Daniel+G.+Taylor) |

<details><summary>Additional details and impacted files</summary>


```diff
@@            Coverage Diff             @@
##             main     #584      +/-   ##
==========================================
- Coverage   92.78%   92.59%   -0.20%     
==========================================
  Files          22       22              
  Lines        3894     3902       +8     
==========================================
  Hits         3613     3613              
- Misses        236      243       +7     
- Partials       45       46       +1     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/danielgtaylor/huma/pull/584?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Daniel+G.+Taylor).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Daniel+G.+Taylor).


Patch:
diff --git a/huma.go b/huma.go
index 32e075f..21d8725 100644
--- a/huma.go
+++ b/huma.go
@@ -16,6 +16,7 @@ import (
 	"io"
 	"net"
 	"net/http"
+	"net/url"
 	"reflect"
 	"regexp"
 	"slices"
@@ -1127,6 +1128,16 @@ func Register[I, O any](api API, op Operation, handler func(context.Context, *I)
 						f.Set(reflect.ValueOf(t))
 						pv = value
 						break
+						// Special case: url.URL
+					} else if f.Type() == urlType {
+						u, err := url.Parse(value)
+						if err != nil {
+							res.Add(pb, value, "invalid url.URL value")
+							return
+						}
+						f.Set(reflect.ValueOf(*u))
+						pv = value
+						break
 					}
 
 					// Last resort: use the `encoding.TextUnmarshaler` interface.


Test patch:
diff --git a/huma_test.go b/huma_test.go
index 435df78..8f11487 100644
--- a/huma_test.go
+++ b/huma_test.go
@@ -11,6 +11,7 @@ import (
 	"net/http"
 	"net/http/httptest"
 	"net/http/httputil"
+	"net/url"
 	"os"
 	"strings"
 	"testing"
@@ -352,6 +353,7 @@ func TestFeatures(t *testing.T) {
 					QueryDefault float32   `query:"def" default:"135" example:"5"`
 					QueryBefore  time.Time `query:"before"`
 					QueryDate    time.Time `query:"date" timeFormat:"2006-01-02"`
+					QueryURL     url.URL   `query:"url"`
 					QueryUint    uint32    `query:"uint"`
 					QueryBool    bool      `query:"bool"`
 					QueryStrings []string  `query:"strings"`
@@ -383,6 +385,7 @@ func TestFeatures(t *testing.T) {
 					assert.InDelta(t, 135, input.QueryDefault, 0)
 					assert.True(t, input.QueryBefore.Equal(time.Date(2023, 1, 1, 12, 0, 0, 0, time.UTC)))
 					assert.True(t, input.QueryDate.Equal(time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)))
+					assert.Equal(t, url.URL{Scheme: "http", Host: "foo.com", Path: "/bar"}, input.QueryURL)
 					assert.EqualValues(t, 1, input.QueryUint)
 					assert.True(t, input.QueryBool)
 					assert.Equal(t, []string{"foo", "bar"}, input.QueryStrings)
@@ -410,10 +413,10 @@ func TestFeatures(t *testing.T) {
 				assert.Equal(t, "Some docs", api.OpenAPI().Paths["/test-params/{string}/{int}/{uuid}"].Get.Parameters[0].Description)
 
 				// `http.Cookie` should be treated as a string.
-				assert.Equal(t, "string", api.OpenAPI().Paths["/test-params/{string}/{int}/{uuid}"].Get.Parameters[28].Schema.Type)
+				assert.Equal(t, "string", api.OpenAPI().Paths["/test-params/{string}/{int}/{uuid}"].Get.Parameters[29].Schema.Type)
 			},
 			Method: http.MethodGet,
-			URL:    "/test-params/foo/123/fba4f46b-4539-4d19-8e3f-a0e629a243b5?string=bar&int=456&before=2023-01-01T12:00:00Z&date=2023-01-01&uint=1&bool=true&strings=foo,bar&ints=2,3&ints8=4,5&ints16=4,5&ints32=4,5&ints64=4,5&uints=1,2&uints16=10,15&uints32=10,15&uints64=10,15&floats32=2.2,2.3&floats64=3.2,3.3&exploded=foo&exploded=bar",
+			URL:    "/test-params/foo/123/fba4f46b-4539-4d19-8e3f-a0e629a243b5?string=bar&int=456&before=2023-01-01T12:00:00Z&date=2023-01-01&url=http%3A%2F%2Ffoo.com%2Fbar&uint=1&bool=true&strings=foo,bar&ints=2,3&ints8=4,5&ints16=4,5&ints32=4,5&ints64=4,5&uints=1,2&uints16=10,15&uints32=10,15&uints64=10,15&floats32=2.2,2.3&floats64=3.2,3.3&exploded=foo&exploded=bar",
 			Headers: map[string]string{
 				"string": "baz",
 				"int":    "789",
@@ -434,6 +437,7 @@ func TestFeatures(t *testing.T) {
 					QueryFloat    float32   `query:"float"`
 					QueryBefore   time.Time `query:"before"`
 					QueryDate     time.Time `query:"date" timeFormat:"2006-01-02"`
+					QueryURL      url.URL   `query:"url"`
 					QueryUint     uint32    `query:"uint"`
 					QueryBool     bool      `query:"bool"`
 					QueryInts     []int     `query:"ints"`
@@ -454,7 +458,7 @@ func TestFeatures(t *testing.T) {
 				})
 			},
 			Method: http.MethodGet,
-			URL:    "/test-params/bad/not-a-uuid?int=bad&float=bad&before=bad&date=bad&uint=bad&bool=bad&ints=bad&ints8=bad&ints16=bad&ints32=bad&ints64=bad&uints=bad&uints16=bad&uints32=bad&uints64=bad&floats32=bad&floats64=bad",
+			URL:    "/test-params/bad/not-a-uuid?int=bad&float=bad&before=bad&date=bad&url=:&uint=bad&bool=bad&ints=bad&ints8=bad&ints16=bad&ints32=bad&ints64=bad&uints=bad&uints16=bad&uints32=bad&uints64=bad&floats32=bad&floats64=bad",
 			Assert: func(t *testing.T, resp *httptest.ResponseRecorder) {
 				assert.Equal(t, http.StatusUnprocessableEntity, resp.Code)
 
@@ -462,6 +466,7 @@ func TestFeatures(t *testing.T) {
 				assert.Contains(t, resp.Body.String(), "invalid value: invalid UUID length: 10")
 				assert.Contains(t, resp.Body.String(), "invalid float")
 				assert.Contains(t, resp.Body.String(), "invalid date/time")
+				assert.Contains(t, resp.Body.String(), "invalid url.URL")
 				assert.Contains(t, resp.Body.String(), "invalid bool")
 				assert.Contains(t, resp.Body.String(), "required query parameter is missing")
 				assert.Contains(t, resp.Body.String(), "required header parameter is missing")