-3

I have a simple web application, the code file which is named HttpServer.go is:

package main

import (
    "net/http"
)

func main() {
    mux := http.NewServeMux()
    files := http.FileServer(http.Dir("/public"))
    mux.Handle("/static/", http.StripPrefix("/static/", files))
    server := &http.Server{
        Addr:    "localhost:8080",
        Handler: mux,
    }
    server.ListenAndServe()
}

I have put the this code file under %GOPATH%/src/first_app, and I go install this program, the first_app.exe shows up in %GOPATH%/bin

When I startup the webserver,I accessed

http://localhost:8080/static/a.txt, but 404(NOT FOUND) complains that a.txt is not found.,

I would ask where should I put the directory public and a.txt

Tom
  • 5,848
  • 12
  • 44
  • 104
  • 3
    Related / Possible duplicate of [Why do I need to use http.StripPrefix to access my static files?](https://stackoverflow.com/questions/27945310/why-do-i-need-to-use-http-stripprefix-to-access-my-static-files/27946132#27946132) – icza Sep 07 '17 at 09:56
  • Also possible duplicate of [With golang webserver where does the root of the website map onto the filesystem?](https://stackoverflow.com/questions/28745161/with-golang-webserver-where-does-the-root-of-the-website-map-onto-the-filesystem/28745280#28745280) – icza Sep 08 '17 at 03:33

1 Answers1

1

It looks in the path you specify in your http.Dir expression. /public in your case.

Most likely you don't have a path called /public on your system (since this is a non-standard directory path on all OSes I'm familiar with, and I suspect you haven't created it).

Change /public to match the path where you put your files.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • where should I create the directory `/public`, is it an absolute directory or a relative directory(eg, relative to the root of app) – Tom Sep 07 '17 at 10:16
  • Thanks @Flimzy. I tried to use an absolute directory,like `files := http.FileServer(http.Dir("c:/public"))`. Now it works. But I wonder whether I can specify a relative path such as relative to the app's root – Tom Sep 07 '17 at 10:20
  • I figured out the relative path,If I am using` files := http.FileServer(http.Dir("public"))`,which has no leading `/`, it will be relative to $GOPATH, so that it will look for $GOPATH/public/a.txt if I request http://localhost:8080/static/a.txt – Tom Sep 07 '17 at 10:26
  • 2
    It is not relative to `GOPATH` - like all relative paths, it is relative to the current working directory (i.e. wherever you ran the app from). – Adrian Sep 07 '17 at 14:33