duanhui1185 2012-01-30 03:50
浏览 76
已采纳

GAE Go,init()-多次调用?

I'm writing a Google App Engine Go application. In it, I want to handle some calls separately in different .go files. Should I call "init()" function separately in each of those files, or just declare it in one file and call some other functions for initialisation of each .go file?

For example, if I'd have two files, user.go:

package User

import(
    "http"
    "fmt"
)

func init() {
    http.HandleFunc("/", hello)
}

func hello(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Hello, user!")
}

And admin.go:

package Admin

import(
    "http"
    "fmt"
)

func init() {
    http.HandleFunc("/admin/", hello)
}

func hello(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Hello, admin!")
}

Is such an initialisation correct, or is it advised against something like this?

  • 写回答

2条回答 默认 最新

  • douren1928 2012-01-30 08:07
    关注

    According to Go language specification:

    • all initialization code is run in a single goroutine, and

    • init() functions within a single package execute in unspecified order

    In your case, the packages User and Admin are independent (User does not import Admin, nor Admin imports User). This means that:

    • the two init() functions in User and Admin execute in unspecified order

    Joining the bodies of the two init() functions in a single init() function would look like this:

    func init() {
        http.HandleFunc("/", User.Hello)
        http.HandleFunc("/admin/", Admin.Hello)
    }
    

    Notice that it is irrelevant whether the program first registers "/" or "/admin/". So, the following code is also valid :

    func init() {
        http.HandleFunc("/admin/", Admin.Hello)
        http.HandleFunc("/", User.Hello)
    }
    

    From the above two snippets of code, we can see that it is OK for http.HandleFunc("/", ...) and http.HandleFunc("/admin/", ...) to be called in unspecified order.


    Because "/" and "/admin/" can be registered in any order, and all init() functions run in a single goroutine, the answer to your question is: Yes, such an initialisation correct.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器