-1

I am creating a Restful API.

I am passing function name and arguments in JSON

eg. "localhost/json_server?method=foo&id=1"

Lets say, i have a simple go server running

 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {                                                                             
     fmt.Println("path",r.URL.Path )                                                                                                             
     fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))                                                                                  
 }) 
.........
function json_server(){
....
}

The r.url.Path will give me "json_server" in string. Now i want to first check if the function exists , if exists call the function as defined else throw some exception.

Is this possible to do ?

When i am doing python and i use getattr(method,args) to call the method and arguments which are in string.

I have developed interest in Go after using Docker. Any help will be appreciated.

Sijan Shrestha
  • 2,136
  • 7
  • 26
  • 52

1 Answers1

4

As far as I know it's not possible to enumerate the functions of a package using the reflection api, but see this mailing list discussion for some ideas involving parsing the source files. Enumerating methods of an object is possible, which is actually more to what you describe in python.

However, I would recommend using a simple dispatch table instead of introspection, you can populate a map[string]func(), though I suspect you might want to pass some arguments to your function, e.g. the request to be handled:

var dispatch map[string]http.HandlerFunc

func init() {
    dispatch = make(map[string]http.HandlerFunc)
    dispatch["json_server"] = json_server
    dispatch["foo"] = func(w http.ResponseWriter, r *http.Request) {
        ...
    }
}

func ServeHTTP (w http.ResponseWriter, r *http.Request) {
    if handler, exists := dispatch[req.URL.Path]; exists {
        handler(w, r)
    } else {
        ... // fallback
    }
}

Or better yet, just use an existing HTTP router, such as httprouter or gorilla/mux. There are many alternatives to choose from.

nothingmuch
  • 1,456
  • 9
  • 10