go - 在 GO 中将字符串转换为函数名称?

标签 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 将在 string 中给我“json_server”。现在我想首先检查该函数是否存在,如果存在则按定义调用该函数,否则抛出一些异常。

这可能吗?

当我在做 python 时,我使用 getattr(method,args) 调用字符串中的方法和参数。

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

最佳答案

据我所知,不可能使用 reflection api 枚举包的功能, 但见 this mailing list discussion对于涉及解析源文件的一些想法。枚举对象的方法 is possible ,这实际上更符合您在 python 中描述的内容。

但是,我建议使用一个简单的调度表而不是内省(introspection),你可以填充一个 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 .有许多备选方案可供选择。

关于go - 在 GO 中将字符串转换为函数名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41206370/

相关文章:

google-app-engine - 在 Google 应用引擎上将 Go 程序(网络爬虫)作为 cron 作业执行

go - 如何在 3 秒内打印此 Go 代码?

go - 如何在windows下运行Go语言?

testing - Go 在运行测试时挂起

go - Go语言错误处理问题/误解?

go - beego 模型错误

json - Go json.NewDecoder().Decode() 似乎不遵守上下文截止日期

Golang 接口(interface)的好处

json - 解码 map[string]interface{} 时出现 mgo 错误

eclipse - 无法在 Windows 上编译/安装插件