I have very simple code, my .go file:
func init() {
http.HandleFunc("/", handlerMain)
log.Println("init executed")
}
func handlerMain(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "TEST")
}
and app.yaml:
application: newsboard
version: 1
runtime: go
api_version: go1
handlers:
- url: /.*
script: _go_app
When Executed at first everything goes fine, this is output from console
INFO 2015-10-19 19:28:56,626 devappserver2.py:763] Skipping SDK update check.
INFO 2015-10-19 19:28:56,652 api_server.py:205] Starting API server at: http://localhost:56946
INFO 2015-10-19 19:28:56,655 dispatcher.py:197] Starting module "default" running at: http://localhost:8080
INFO 2015-10-19 19:28:56,658 admin_server.py:116] Starting admin server at: http://localhost:8000
2015/10/19 19:28:59 init executed
But when I Enter http://localhost:8080 I get following:
INFO 2015-10-19 19:32:16,394 module.py:786] default: "GET / HTTP/1.1" 200 4
2015/10/19 19:32:16 init executed
So init() somehow is being executed twice. Then, Every time when I reload page everething is ok,"init executed" doesn't appear in console anymore. My question: Why init() happens twice and is this okay?
It is perfectly fine.
The Go AppEngine SDK monitors the application's code base, and whenever it detects changes (e.g. you modified a .go
source file) it automatically reloads your application. This includes / involves unloading your code and reloading it - running init()
functions again.
Basically control over when an app is reloaded - and therefore execution of the init()
functions - is in the "hands" of the SDK. Try to modify a .go
file and hit refresh in the browser: you will experience another init()
function execution.
When you first start your app, all the code is loaded/compiled (and init()
functions get executed) - this needs to be done in order to report if there are errors. After that the SDK may unload it (not sure - couldn't find relevant docs) and only load it again if a request does happen (which may or may not come anytime soon).