Search code examples
httpgofileserver

Why my fileServer handler doesn't work?


I've a simple folder :

Test/
    main.go
    Images/
          image1.png
          image2.png
          index.html

In main main.go I just put :

package main

import (
       "net/http"
)

func main(){
     fs := http.FileServer(http.Dir("./Images"))
     http.Handle("/Images/*", fs)
     http.ListenAndServe(":3003", nil)
}

But when I curl on http://localhost:3003/Images/ or even I add to path file's name, it doesn't work. I don't understand because it's the same as the reply given on this subject

Can you tell me so that this does not work ?


Solution

  • You need to remove * and add extra sub-folder Images:
    This works fine:

    Test/
        main.go
        Images/
              Images/
                    image1.png
                    image2.png
                    index.html
    

    Code:

    package main
    
    import (
        "net/http"
    )
    
    func main() {
        fs := http.FileServer(http.Dir("./Images"))
        http.Handle("/Images/", fs)
        http.ListenAndServe(":3003", nil)
    }
    

    Then go run main.go

    And:

    http://localhost:3003/Images/


    Or simply use:

    package main
    
    import (
        "net/http"
    )
    
    func main() {
        fs := http.FileServer(http.Dir("./Images"))
        http.Handle("/", fs)
        http.ListenAndServe(":3003", nil)
    }
    

    with: http://localhost:3003/