dongzizhi9903 2016-12-18 07:37
浏览 177
已采纳

在GO中将字符串转换为函数名称? [重复]

This question already has an answer here:

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.

</div>
  • 写回答

1条回答 默认 最新

  • dongnao2048 2016-12-18 08:06
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问Ubuntu要怎么安装chrome呀?
  • ¥15 视频编码 十六进制问题
  • ¥15 Xsheii7我安装这个文件的时候跳出来另一个文件已锁定文件的无一部分进程无法访问。这个该怎么解决
  • ¥15 unity terrain打包后地形错位,跟建筑不在同一个位置,怎么办
  • ¥15 FileNotFoundError 解决方案
  • ¥15 uniapp实现如下图的图表功能
  • ¥15 u-subsection如何修改相邻两个节点样式
  • ¥30 vs2010开发 WFP(windows filtering platform)
  • ¥15 服务端控制goose报文控制块的发布问题
  • ¥15 学习指导与未来导向啊