FileServer handler with some other HTTP handlers

I’m trying to start a HTTP server in Go that will serve my own data using my own handlers, but at the same time I would like to use the default http FileServer to serve files.

I’m having problems to make the handler of the FileServer to work in a URL subdirectory.

This code is not working:

package main

import (

func main() {
        http.Handle("/files/", http.FileServer(http.Dir(".")))
        http.HandleFunc("/hello", myhandler)

        err := http.ListenAndServe(":1234", nil)
        if err != nil {
                log.Fatal("Error listening: ", err)

func myhandler(w http.ResponseWriter, req *http.Request) {
        fmt.Fprintln(w, "Hello!")

I was expecting to find the local directory in localhost:1234/files/ but it returns a 404 page not found .

However, if I change the handler address of the fileserver to /, it works:

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

But now my files are accessible and visible at the root directory.

How can I make it to serve files from a different URL than root?

1 Like

You need to use the http.StripPrefix handler:

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

See here:

Refer: stackoverflow