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

Wrap handler easily #289

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

champon1020
Copy link

@champon1020 champon1020 commented Dec 11, 2019

Why

Because I want to use middleware in the way which is similar to net/http.

How to fix

I added method of ServeHTTP to httprouter.Handle.
Then, you can use middleware like this.

func myHandler(w http.ResponseWriter, r *http.Request, ps Params) {
    ...
    
    fmt.Println("some process")

    ...
}

func middleware(h httprouter.Handle) httprouter.Handle {
    return func(w http.ResponseWriter, r *http.Request, ps Params) {
        ...
        
        fmt.Println("some process")

        ...

        h.ServeHTTP(w, r, ps)
    }
}

func main() {
    r := httprouter.New()
    r.GET("/route", middleware(myHandler))

    ...
}

Additional

Created test.

Copy link
Owner

@julienschmidt julienschmidt left a comment

Choose a reason for hiding this comment

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

In general this change absolutely makes sense. Thank you!

Kindly change the godoc for ServeHTTP as written above, though.

router.go Outdated
@@ -88,6 +88,11 @@ import (
// wildcards (path variables).
type Handle func(http.ResponseWriter, *http.Request, Params)

// ServeHTTP calls function type of Handle.
Copy link
Owner

Choose a reason for hiding this comment

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

Please align this with the comment for http.HandlerFunc.ServeHTTP: ServeHTTP calls h(w, r, ps).

Copy link
Author

Choose a reason for hiding this comment

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

Thank you for reviewing my code!
I've just fixed the comment that you have pointed out.

@fsaintjacques
Copy link

Could you merge this?

@champon1020
Copy link
Author

@fsaintjacques I'm sorry I can't, I have no right to merge without approval.
I'm waiting for re-approval of my modification from @julienschmidt now.

@fsaintjacques
Copy link

@julienschmidt gentle ping.

similark pushed a commit to similarweb/httprouter that referenced this pull request May 9, 2023
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.

3 participants