1

I have a solution that works, but I want to fine tune it and at the same time understand how it works.

Here is my folder structure:

web/
├── main.go
└── public/
      ├── css/
      ├── js/
      ├── img/
      │    └── pict.jpg
      └── templates/

The current path that works to get a picture is:

<img src="public/img/pict.jpg"></a>

The desired path to get a picture is (I want to skip the public/ part):

<img src="img/pict.jpg"></a>

The relevant go code:

func main() {
    http.HandleFunc("/", index)
    http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("./public"))))
    http.ListenAndServe(":8080", nil)
}

The same short path should also apply on css and js folder. TIA!

sibert
  • 1,968
  • 8
  • 33
  • 57
  • 1
    This possible duplicate explains it: [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 Feb 21 '19 at 15:05
  • If you want that shorter path, then it would need to be handled by the "/" route. Can you have an index.html in your public directory? Or do you need a custom 'index' handler? – colm.anseo Feb 21 '19 at 15:10
  • @colminator Being a newbie, I assume that the path to templates folder is handled by ParseGlob path. Not the Fileserver. Correct? – sibert Feb 21 '19 at 15:13
  • @icza This question / answers does not give any clue about path to 3 subfolders as far as I can see. – sibert Feb 21 '19 at 15:16
  • 1
    The router picks the shortest match. So `/public/img/...` matches the 2nd route. But `/img/...` - what you want - falls under the 1st route. – colm.anseo Feb 21 '19 at 15:17
  • 1
    You could add individual routes for /img /css and /js - it's up to you. – colm.anseo Feb 21 '19 at 15:18
  • @colminator I do not know which of them I should edit. There is a number of combinations. And is there no way to get One single route for all three folders js, img and css? – sibert Feb 21 '19 at 15:27

1 Answers1

1

Try this: downside is you need to repeat this for each sub-directory

http.HandleFunc("/", index)

http.Handle("/img/",
    http.StripPrefix("/img/", http.FileServer(http.Dir("./public/img"))))
http.Handle("/css/",
    http.StripPrefix("/css/", http.FileServer(http.Dir("./public/css"))))

// ... etc.
colm.anseo
  • 19,337
  • 4
  • 43
  • 52
  • This works. Thank you! Is it possible to avoid repeating for each subfolder? – sibert Feb 21 '19 at 15:55
  • Since you have a route on "/" - unfortunately no. If you had the FileServer on "/" - it would work - but then you could not trigger your `index` handler - as the fileserver would catch all routes. This is why most sites put static files in "/assets" or "/static" path - so one only needs one fileserver to handle all those files. – colm.anseo Feb 21 '19 at 16:05