0

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
sean
  • 3,484
  • 5
  • 27
  • 45

2 Answers2

5

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.

Michael Hampton
  • 9,737
  • 4
  • 55
  • 96
3

The path you give to http.Dir is relative to where the application is run (its working directory, the root of the directory tree you posted, in your case) and not relative to where the .go file is. Just change the path to ./web/views and it should work.

In your case, the 404 Not Found is returned, because there is no views folder at the top level of your directory tree and therefore there are no files to be served.

Leon
  • 2,926
  • 1
  • 25
  • 34