0

I want to extend the http.Request structure to include arguments present in the url. I know there are excellent libraries like gorilla that already do this, but I want to learn how its done on the nuts and bolts level.

Here's an example of what I'm trying to do:

// server.go

func Vars(r *http.Request) map[string]string {
    var args map[string]string
    args = make(map[string]string)
    s := r.URL.Path.split('/')[1:]
    for str := range s {
        _, arg, _ := regexp.MatchString("\{\w+\}", str)
        append(args, arg)
    }

    return args
}

httpMock.HandleFunc("/myurl/{arg1}/", MyHandler)

func MyHandler(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Success! " + r.Vars()["arg1"]))
}

But I get an index out of range exception. Can anyone help me figure out how to do this?

dopatraman
  • 13,416
  • 29
  • 90
  • 154
  • A good starting point would be breaking out `w.Write([]byte("Success! " + r.Vars()["arg1"]))` so that you can inspect the return value of `Vars()`. I'd have to verify this but there might be a language rule which requires methods for a type are defined in the same package as the type in which case you'll want to make your own Request type that embeds the `http.Request` type. If you can update with the return value of `Vars()` I might be able to supply a complete answer. – evanmcdonnal Apr 07 '16 at 22:07
  • Which line raises the index out of bounds error? – Charlie Tumahai Apr 07 '16 at 22:40
  • Use slice instead of array. I just though it would be better. This line. s := r.URL.Path.split('/')[1:] – atilkan Apr 07 '16 at 23:01
  • And if there is no parameters coming. (Forex:index page) You get an error. There is no object at 1. – atilkan Apr 07 '16 at 23:04
  • well, speaking of `extend`, its just plain o` adapter design pattern. For more insights: http://stackoverflow.com/questions/36490162/inheritance-on-built-in-library-in-golang – Roy Lee Apr 08 '16 at 03:17
  • Are you looking for something like "type Request struct { http.Request, innerHtml string}"? That'd allow you to use the methods and variables, as well as add on your own methods and variables. – user161778 Apr 08 '16 at 23:50

0 Answers0