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

feat: remove chi dependency #8

Merged
merged 3 commits into from
Jan 29, 2025
Merged

feat: remove chi dependency #8

merged 3 commits into from
Jan 29, 2025

Conversation

rluders
Copy link
Owner

@rluders rluders commented Jan 29, 2025

Summary by CodeRabbit

Release Notes

  • New Features

    • Added support for Gorilla MUX, Chi, and Go Standard routers.
    • Enhanced request parsing with flexible router parameter extraction.
    • Introduced example implementations for handling HTTP requests with different routers.
  • Documentation

    • Updated README with supported routers information.
    • Updated installation instructions to use versioned import path.
  • Chores

    • Updated dependencies to latest versions.
    • Migrated project to version 2 of the library.

Copy link

coderabbitai bot commented Jan 29, 2025

Walkthrough

This pull request introduces significant changes to the httpsuite library, focusing on enhancing router support and modularizing the request parsing mechanism. The library now supports multiple routers (Gorilla MUX, Chi, and Go Standard) with a flexible parameter extraction approach. The project has been updated to version 2, with changes to the module structure, dependency management, and example implementations across different routing libraries.

Changes

File Change Summary
README.md - Added "Supported routers" section
- Updated installation command to go get github.com/rluders/httpsuite/v2
- Removed usage example section
go.mod - Updated module to github.com/rluders/httpsuite/v2
- Updated dependency versions
request.go - Added ParamExtractor function type
- Modified ParseRequest to accept parameter extractor
examples/chi/go.mod - New module declared as chi_example
- Go version specified as 1.23
- Added dependencies for Chi and httpsuite
examples/chi/main.go - Introduced a new Go application using Chi router
- Defined SampleRequest and SampleResponse types
- Implemented POST endpoint at /submit/{id}
examples/gorillamux/go.mod - New module declared as gorillamux_example
- Go version specified as 1.23
- Added dependencies for Gorilla Mux and httpsuite
examples/gorillamux/main.go - Introduced a new Go application using Gorilla Mux router
- Defined SampleRequest and SampleResponse types
- Implemented POST endpoint at /submit/{id}
examples/stdmux/go.mod - New module declared as stdmux_example
- Go version specified as 1.23
- Added dependency for httpsuite
examples/stdmux/main.go - Introduced a new Go application using Standard Mux router
- Defined SampleRequest and SampleResponse types
- Implemented POST endpoint at /submit/
examples/main.go - Removed previous main.go file containing Chi router implementation
request_test.go - Added MyParamExtractor function for parameter extraction
- Updated Test_ParseRequest to utilize new parameter extraction method

Possibly related PRs

Poem

🐰 Hop, hop, through routers we go,
Parsing requests with flexible flow
Chi, Mux, and Standard, all in sight
httpsuite v2 shines so bright!
Params extracted with rabbit-like grace 🚀


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7501c7e and 17ec903.

📒 Files selected for processing (4)
  • examples/chi/go.mod (1 hunks)
  • examples/gorillamux/go.mod (1 hunks)
  • examples/stdmux/go.mod (1 hunks)
  • go.mod (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • go.mod
  • examples/stdmux/go.mod
  • examples/gorillamux/go.mod
  • examples/chi/go.mod

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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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 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 for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (8)
examples/gorillamux/main.go (3)

23-33: Parameter setter pattern is flexible.

Implementing SetParam to populate individual fields from the URL parameter fosters reusability. Consider gracefully handling unknown fields to avoid silent failures.


35-37: Router-specific extractor.

Using mux.Vars(r) is a recognized approach with Gorilla Mux. This function is simple, but if additional logic is needed (e.g., type checking or boundary checks), consider adding it here.


45-66: Endpoint and server logic.

  1. The ParseRequest usage with GorillaMuxParamExtractor is a good demonstration of decoupling router logic from request parsing.
  2. Consider handling the error from ListenAndServe (e.g., log.Fatal(http.ListenAndServe(":8080", r))) to avoid silent failures.
🧰 Tools
🪛 golangci-lint (1.62.2)

47-47: undefined: httpsuite

(typecheck)


60-60: undefined: httpsuite

(typecheck)

examples/stdmux/main.go (1)

45-71: HTTP server usage.

  1. Using ParseRequest with StdMuxParamExtractor demonstrates the router-agnostic design.
  2. Consider handling errors from http.ListenAndServe to make debugging easier.
🧰 Tools
🪛 golangci-lint (1.62.2)

52-52: undefined: httpsuite

(typecheck)


65-65: undefined: httpsuite

(typecheck)

examples/chi/main.go (1)

24-34: Consider enhancing error handling in SetParam.

The error message could be more descriptive to help diagnose issues.

-			return err
+			return fmt.Errorf("failed to parse id '%s': %w", value, err)
request_test.go (1)

38-48: Enhance MyParamExtractor implementation.

The current implementation has limitations:

  1. Only supports "ID" parameter
  2. Assumes fixed URL structure
  3. No validation for malformed paths
 func MyParamExtractor(r *http.Request, key string) string {
 	pathSegments := strings.Split(r.URL.Path, "/")
-	// You should know how the path is structured; in this case, we expect the ID to be the second segment.
-	if len(pathSegments) > 2 && key == "ID" {
-		return pathSegments[2]
+	// Map path segments to parameter names
+	paramMap := map[string]int{
+		"ID": 2,
+		// Add more parameters as needed
+	}
+	if pos, ok := paramMap[key]; ok && len(pathSegments) > pos {
+		return pathSegments[pos]
 	}
 	return ""
 }
README.md (2)

26-28: Add language identifier to code block.

The installation code block should specify the language for better syntax highlighting.

-```
+```bash
 go get github.com/rluders/httpsuite/v2

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 markdownlint-cli2 (0.17.2)</summary>

26-26: Fenced code blocks should have a language specified
null

(MD040, fenced-code-language)

</details>

</details>

---

`31-33`: **Consider adding quick start examples.**

The Usage section could benefit from quick start examples for each supported router, showing the basic setup and request handling.

I can help generate example code snippets for each supported router if you'd like.

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used: CodeRabbit UI**
**Review profile: CHILL**
**Plan: Pro**

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 3363c157b42deacabd322b95ba93e623512dc380 and 7501c7e1dbff878126543f9b7973e07117373720.

</details>

<details>
<summary>⛔ Files ignored due to path filters (4)</summary>

* `examples/chi/go.sum` is excluded by `!**/*.sum`
* `examples/gorillamux/go.sum` is excluded by `!**/*.sum`
* `examples/stdmux/go.sum` is excluded by `!**/*.sum`
* `go.sum` is excluded by `!**/*.sum`

</details>

<details>
<summary>📒 Files selected for processing (11)</summary>

* `README.md` (1 hunks)
* `examples/chi/go.mod` (1 hunks)
* `examples/chi/main.go` (1 hunks)
* `examples/gorillamux/go.mod` (1 hunks)
* `examples/gorillamux/main.go` (1 hunks)
* `examples/main.go` (0 hunks)
* `examples/stdmux/go.mod` (1 hunks)
* `examples/stdmux/main.go` (1 hunks)
* `go.mod` (1 hunks)
* `request.go` (1 hunks)
* `request_test.go` (7 hunks)

</details>

<details>
<summary>💤 Files with no reviewable changes (1)</summary>

* examples/main.go

</details>

<details>
<summary>✅ Files skipped from review due to trivial changes (3)</summary>

* examples/stdmux/go.mod
* examples/gorillamux/go.mod
* examples/chi/go.mod

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🪛 markdownlint-cli2 (0.17.2)</summary>

<details>
<summary>README.md</summary>

26-26: Fenced code blocks should have a language specified
null

(MD040, fenced-code-language)

</details>

</details>
<details>
<summary>🪛 golangci-lint (1.62.2)</summary>

<details>
<summary>examples/chi/main.go</summary>

58-58: undefined: httpsuite

(typecheck)

---

71-71: undefined: httpsuite

(typecheck)

</details>
<details>
<summary>examples/stdmux/main.go</summary>

52-52: undefined: httpsuite

(typecheck)

---

65-65: undefined: httpsuite

(typecheck)

</details>
<details>
<summary>examples/gorillamux/main.go</summary>

47-47: undefined: httpsuite

(typecheck)

---

60-60: undefined: httpsuite

(typecheck)

</details>

</details>

</details>

<details>
<summary>🔇 Additional comments (15)</summary><blockquote>

<details>
<summary>request.go (6)</summary>

`18-28`: **Flexible URL parameter extraction looks good!**

Introducing the `ParamExtractor` type is an elegant solution. It removes the tight coupling to a specific router (e.g., Chi) and allows more flexible usage with various routers.

---

`30-59`: **Comprehensive documentation.**

The enhanced doc comments thoroughly explain the usage of `ParseRequest`, including how the new `paramExtractor` function is leveraged. This is beneficial for both maintainers and new users alike.

---

`62-66`: **Good practice closing request body.**

Using `defer func() { _ = r.Body.Close() }()` ensures that the request body is properly closed, preventing resource leaks. The JSON decoding and error response logic is concise and correct.

---

`76-78`: **Parameter extraction error handling is appropriate.**

Returning a bad request status if a URL parameter is missing accurately communicates the nature of the error. This behavior is consistent with typical REST API expectations.

---

`82-82`: **Useful internal server error response.**

When `SetParam` fails, responding with a 500 makes sense, as this indicates an internal issue mapping the parameter. The `Details` field includes the actual error, which is helpful for debugging.

---

`88-88`: **Validation error handling is consistent.**

A structured validation error message with status 400 aligns with typical REST conventions, improving transparency for the client.

</details>
<details>
<summary>examples/gorillamux/main.go (3)</summary>

`11-15`: **Request struct is well-defined.**

The `SampleRequest` with validation tags looks good. Ensure unit or integration tests exist to validate that requests missing the required fields trigger the appropriate error handling.

---

`17-21`: **Response struct is straightforward.**

Structuring the response as a separate entity is good practice, providing a clean separation of input (request) and output (response) data.

---

`1-9`: **Dependency on local package reference.**

The static analysis tool flagged `undefined: httpsuite`. Confirm that the import path (`github.com/rluders/httpsuite/v2`) is correct and available in your local environment or go.mod.

</details>
<details>
<summary>examples/stdmux/main.go (4)</summary>

`10-14`: **Well-structured request fields with validation tags.**

Make sure to cover boundary cases in tests (e.g., missing or short values for `Name`, negative or zero values for `Age`).

---

`16-20`: **Clear separation of response data.**

A dedicated response struct is a clean approach, ensuring the server has a consistent output format.

---

`22-32`: **Robust param setter.**

The approach of converting `id` from string to int is standard. As a future improvement, consider validating the result to ensure it meets any domain-specific constraints (e.g., positive IDs).

---

`1-8`: **Dependency on local package reference.**

Similar to the Gorilla Mux file, ensure `github.com/rluders/httpsuite/v2` is properly set up in your modules. The static analysis warnings might be due to an incomplete local setup.

</details>
<details>
<summary>examples/chi/main.go (1)</summary>

`6-6`: **Update import path to use a specific version.**

The import path `github.com/rluders/httpsuite/v2` should specify a version constraint to ensure reproducible builds.

</details>
<details>
<summary>request_test.go (1)</summary>

`107-107`: **LGTM! Test cases properly validate the new parameter extraction.**

The test cases effectively cover the new parameter extraction functionality while maintaining existing behavior.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

@rluders
Copy link
Owner Author

rluders commented Jan 29, 2025

@coderabbitai review

Copy link

coderabbitai bot commented Jan 29, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@rluders rluders merged commit f081d27 into main Jan 29, 2025
2 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Jan 31, 2025
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

Successfully merging this pull request may close these issues.

1 participant