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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵