Dany
Dany

Reputation: 2802

http HandleFunc argument in golang

I want to use a rate limiting or throttler library to limit the number of client requests. I use a vendor library in my code base. I want to pass in a ResponseWriter, Request and a third variable retrieved from the URL. When I use the library for throttling, it gives me back a handler that only handles two arguments. How can I pass my third argument into the handler?

Here is my current code:

package main

import (
    "fmt"
    "github.com/didip/tollbooth"
    "net/http"
    )

func viewHandler(
    w http.ResponseWriter, 
    r *http.Request, 
    uniqueId string,
    ) {
    //data := getData(uniqueId)
    fmt.Println("Id:", uniqueId)
    p := &objects.ModelApp{LoggedUser: "Ryan Hardy", ViewData: "data"}
    renderTemplate(w, "view", p)
}

//URL validation for basic web services
var validPath = regexp.MustCompile("^/$|/(home|about|view)/(|[a-zA-Z0-9]+)$")

func makeHandler(
    fn func(
        http.ResponseWriter, 
        *http.Request, string,
        )) http.HandlerFunc {
    return func(
        w http.ResponseWriter, 
        r *http.Request,
        ) {
        m := validPath.FindStringSubmatch(r.URL.Path)
        if m == nil {
            http.NotFound(w, r)
            return
        }
        fn(w, r, m[2])
    }
}

func main() {
    http.Handle("/view/", makeHandler(tollbooth.LimitFuncHandler(tollbooth.NewLimiter(1, time.Second), viewHandler)))
    http.ListenAndServe(":8080", nil)
}

Could anyone help me with this?

Upvotes: 1

Views: 4041

Answers (1)

Datsik
Datsik

Reputation: 14824

I'm on my phone so this may be difficult to type but you could use the http.Handle function which takes an interface of Handler something like

type makeHandler struct {
    YourVariable string
}

func (m *makeHandler) ServeHTTP (w http.ResponseWriter, r *http.Request) {
    yourVariableYouNeed := m.YourVariable
    // do whatever 
    w.Write()
}

// do whatever you need to get your variable
blah := &makeHandler{ yourThing }

http.Handle("/views", blah)

On my phone so can't test but it should work, let me know if it doesn't.

Upvotes: 1

Related Questions