1

Hi I am trying to create a server in Go Lang which serves files and HTTP Requests at the same time.

I want /upload path to accept post requests and /files path to serve static files in the fpath

I tried with the following code but i get a 404 error

func main() {
    fpath, _ := filepath.Abs(filepath.Dir(os.Args[0]))
    fpath+="/public"
    fmt.Println(fpath)
    http.HandleFunc("/upload",uploadFunc)
    http.HandleFunc("/files",http.FileServer(http.Dir(fpath)))
    panic(http.ListenAndServe(":8080", nil))
}
4
  • you don't mention at all what kind of technology you are using... Commented Aug 20, 2014 at 5:09
  • oops i just added the tag Commented Aug 20, 2014 at 5:35
  • You should check out http.StripPrefix. Right now, your http.FileServer is trying to serve routes like "/files/foo" (and thus looking for "./public/files/foo") instead of stripping the "/files" prefix off. I tried this myself and it still didn't work, so there's probably something else wrong, but you'll definitely need to do that anyway. Commented Aug 20, 2014 at 6:09
  • 1
    Try http.Handle("/files/", http.StripPrefix("/files/", http.FileServer(http.Dir(fpath)))) instead of HandleFunc(). Please note the trailing slashes on "/files/". Commented Aug 20, 2014 at 9:10

1 Answer 1

3

You need trailing slashes on your handle path if it's a directory. See http://golang.org/pkg/net/http/#ServeMux for more info.

Patterns name fixed, rooted paths, like "/favicon.ico", or rooted subtrees, like "/images/" (note the trailing slash).

Try

func main() {
    fpath, _ := filepath.Abs(filepath.Dir(os.Args[0]))
    fpath+="/public"
    fmt.Println(fpath)
    http.HandleFunc("/upload",uploadFunc)
    http.Handle("/files/", http.StripPrefix("/files/", http.FileServer(http.Dir(fpath))))
    panic(http.ListenAndServe(":8080", nil))
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.