我想用Goji和Google App Engine / Go开发应用程序。
我从中复制并粘贴了示例代码 https://github.com/zenazn/goji并将func名称从“main”更改为“init”。
package main
import (
"fmt"
"net/http"
"github.com/zenazn/goji"
"github.com/zenazn/goji/web"
)
func hello(c web.C, w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", c.URLParams["name"])
}
func init() {
goji.Get("/hello/:name", hello)
goji.Serve()
}
并运行此应用程序
# goapp serve
但是这个应用程序说
bad runtime process port ['']
2014/06/01 08:35:30.125553 listen tcp :8000: bind: address already in use
如何将Goji与GAE / Go一起使用?或者我不能将Goji与GAE / Go一起使用?
答案 0 :(得分:5)
init
函数很特殊,因为它们会自动运行以初始化模块。通过在init函数中为app提供服务,您已经在中途停止了代码的初始化(因为goji.Serve
永远不会终止)。可能发生的事情是某些东西取决于运行时标志,并且在解析它们之前就已经运行了。
您可以做的是编写一个单独的应用引擎处理程序来转发服务goji.DefaultMux
。我没有测试过,但这样的事情应该有效:
import (
"fmt"
"github.com/zenazn/goji"
"net/http"
)
func init() {
http.Handle("/", goji.DefaultMux)
... Register your goji handlers here
}
答案 1 :(得分:2)
这在我的开发服务器中运行良好。
package main
import (
"fmt"
"net/http"
"github.com/zenazn/goji"
"github.com/zenazn/goji/web"
)
func index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "index page")
}
func hello(c web.C, w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", c.URLParams["name"])
}
func init() {
http.Handle("/", goji.DefaultMux)
goji.Get("/", index)
goji.Get("/hello/:name", hello)
}