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 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?