Go 如何使用相对路径中的模板设置http路由测试?
我正在用gorilla/mux编写一个小的web应用程序。我的Go 如何使用相对路径中的模板设置http路由测试?,go,Go,我正在用gorilla/mux编写一个小的web应用程序。我的GOPATH中的文件夹结构如下所示 app/ - app.go - views/ - layout.html - login/ - login.go - login_test.go - login.html package login import ( "net/http" "net/http/httptest" "testing" "." ) func TestHan
GOPATH
中的文件夹结构如下所示
app/
- app.go
- views/
- layout.html
- login/
- login.go
- login_test.go
- login.html
package login
import (
"net/http"
"net/http/httptest"
"testing"
"."
)
func TestHandleGetLogin(t *testing.T) {
request, _ := http.NewRequest("GET", "/", nil)
response := httptest.NewRecorder()
login.GetLogin(response, request)
t.Log(response)
}
我想把登录
作为一个完全独立的包。在login.go
中,我启动模板并根据请求呈现它。当我在主app/
文件夹中运行go-run-app.go
时,所有文件路径都是相对于app.go
的
package login
var view = template.Must(template.ParseFiles(
"login/login.html",
"views/layout.html",
))
func GetLogin(w http.ResponseWriter, r *http.Request) {
err := view.ExecuteTemplate(w, "layout", nil)
check(err)
}
这很好,我可以在我的app.go
文件中调用路线
import (
"github.com/zemirco/app/login"
)
func main() {
router := mux.NewRouter()
router.HandleFunc("/login", login.GetLogin).Methods("GET")
http.Handle("/", router)
http.ListenAndServe(":"+os.Getenv("PORT"), nil)
}
我的问题是测试此路线。在login\u test.go
中,我有类似的东西
app/
- app.go
- views/
- layout.html
- login/
- login.go
- login_test.go
- login.html
package login
import (
"net/http"
"net/http/httptest"
"testing"
"."
)
func TestHandleGetLogin(t *testing.T) {
request, _ := http.NewRequest("GET", "/", nil)
response := httptest.NewRecorder()
login.GetLogin(response, request)
t.Log(response)
}
每当我运行go-test-login/login\u-test.go
时,我都会收到错误消息
打开login/login.html:没有这样的文件或目录
据我所知,go test
从login/
目录中执行,因此无法找到html文件。相对文件路径错误
如何解决这个问题,或者什么是更好的目录结构?Go test接受一个包而不是一个文件,请尝试
Go test./login
测试登录包。那不行。我创建了一个回购协议来证明我的问题-