Need help about http.FileServer(), http.Dir() & http.StripPrefix()

Hello gophers,

I would like to know how http,FileServer(), http.Dir() & http.StripPrefix() work. Detailed and with examples please. I searched about them but I really couldn’t understood how they actually work.

I couldn’t understood why http.Dir() is for. Just for converting the path from string to dir struct(?) or spesific variable type? Also I would like to know what’s the difference between them and how should I write a path:

Why I can’t use http,FileServer() like in the example below, why should I use http.Dir()?:

I really couldn’t understood much about strip prefix function so if someone could help me I would really appreciate it.

Thanks in advance, have a nice day :slight_smile:

Hello Pavin,

I have posted an example through which the difference can be explained.

func main() {

http.Handle("/", http.FileServer(http.Dir("…/")))

http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("."))))

http.ListenAndServe(":8011", nil)


http.Dir(“xxx”) : It returns a filesystem. A file system is a logical collection of files on a partition or disk. In this case, the collection of files will be the list of files present in the folder we passed as an input to http.Dir()

http.FileServer(); It takes a filesystem(return value http.Dir()) and creates an handler. The handler will in turn return all the files listed by http.Dir to the client. If you run the server and execute http://localhost:8011, http.Fileserver will list the files present in the directory you passed as an input to http.Dir()

http.Stripprefix: It is just to strip/remove a prefix from the URL path. Let’s assume we have hanlders defined for “/” path, but we receive the request URL like http://localhost:8011/static/, in this case, if the prefix “static” is not removed, you will receive 404 not found. So, remove the prefix static using the stripprefix function.

You can run the run the server code I have pasted and check it and change it for yourself.

Hi deadpoet,

First of all thank you for your help.
Actually i think I understood how they work but should the website path and the first parameter of the stripprefix function always be the same?

func FileServer(root FileSystem) Handler

type FileSystem interface { Open(name string) (File, error) }

So for example my go file path is home/user/Documents/main.go also i want to host this folder:
/home/user/Documents/static. If the web path is localhost/static, it tries to host /home/user/Documents/static/static* so we should strip that prefix and host /home/user/Documents/static is that right?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.