Shenal Silva
Shenal Silva

Reputation: 2053

Serving HTTP Requests and Files using same server in Go Lang

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))
}

Upvotes: 1

Views: 991

Answers (1)

Intermernet
Intermernet

Reputation: 19418

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))
}

Upvotes: 3

Related Questions