gogo-http

"http.FileServer(http.Dir...))" not working in separate package


Directory tree:

.
├── main.go
└── web
    ├── app.go
    └── views
        ├── index.html
        └── js
            └── app.jsx

This works:

package main

import (
    "net/http"
)

func main() {
    http.Handle("/", http.FileServer(http.Dir("./web/views")))
    http.ListenAndServe(":3000", nil)
}

But this returns 404 page not found:

main.go:

package main

import (
    "{dir with main.go}/web"
)

func main() {
    web.StartHttp()
}

app.go:

package web

import (
    "fmt"
    "net/http"
)

func StartHttp() {
    fmt.Println("STARTHTTP - CHECK 01")

    http.Handle("/", http.FileServer(http.Dir("./views")))
    http.ListenAndServe(":3000", nil)
}

The terminal prints STARTHTTP - CHECK 01, so the StartHttp() function is called, and the terminal asks to allow incoming network connections, so the http server seems to be listening on the port.

Is there some type of context not being passed to the other package?


Solution

  • Remember that Go is a compiled language; most everything the program does happens at runtime.

    In particular, in this case, the call to http.Dir() happens at runtime, and that means that the path is evaluated at runtime.

    Because the path you have given is relative, it is therefore relative to the working directory from which you run the application. The directory in which the source code resided is not relevant here.

    In one invocation to http.Dir() you give the argument ./web/views, but in the other, you give the argument ./views. It turns out that the correct path based on the directory from which you executed the program was ./web/views. When you execute the program with the wrong path, you get 404 page not found errors because the path specified did not exist in your working directory.