如何在相对路径中使用模板设置http路由测试?

时间:2014-09-30 11:33:46

标签: go

我正在用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 testlogin/目录中执行,因此无法找到html文件。相对文件路径错误。

如何解决此问题或更好的目录结构?

0 个答案:

没有答案