我正在用gorilla / mux编写一个小型Web应用程序。我GOPATH
中的文件夹结构是这样的。
app/
- app.go
- views/
- layout.html
- login/
- login.go
- login_test.go
- login.html
我想将login
保留为一个完全独立的包。在login.go
内我启动模板并根据请求呈现它。当我在主app.go
文件夹中运行go run app.go
时,所有文件路径都与app/
相关。
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_test.go
内,我有类似的东西。
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_test.go
时,我都会收到错误消息
open login / login.html:没有这样的文件或目录
据我所知go test
从login/
目录中执行,因此无法找到html文件。相对文件路径错误。
如何解决此问题或更好的目录结构?