Convert String to Function name in GO?

huangapple go评论79阅读模式
英文:

Convert String to Function name in GO?

问题

我正在创建一个Restful API。

我正在使用JSON传递函数名和参数。

例如:"localhost/json_server?method=foo&id=1"

假设我有一个简单的Go服务器正在运行:

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(){
    ....
}

r.URL.Path将以字符串形式给出"json_server"。现在,我想首先检查函数是否存在,如果存在,则按照定义调用该函数,否则抛出一些异常。

这个能做到吗?

当我使用Python时,我使用getattr(method,args)来调用以字符串形式给出的方法和参数。

在使用Docker之后,我对Go产生了兴趣。任何帮助将不胜感激。

英文:

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.

答案1

得分: 4

据我所知,使用反射API无法枚举包的函数,但可以查看这个邮件列表讨论以获取涉及解析源文件的一些想法。在Python中,可以枚举对象的方法,这实际上更符合你的描述。

然而,我建议使用简单的调度表而不是内省,你可以创建一个map[string]func(),尽管我猜你可能想将一些参数传递给函数,例如要处理的请求:

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
    }
}

或者更好的办法是,使用现有的HTTP路由器,比如httproutergorilla/mux。有很多选择。

英文:

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.

huangapple
  • 本文由 发表于 2016年12月18日 15:37:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/41206370.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定