xaos_xv
xaos_xv

Reputation: 769

Golang FileServer with custom css

I've thought about creating a mini file server for my home with Go. Normally http.FileServer servers files and dirs ugly like this:

enter image description here

Is it possible to add CSS to this site? For example change colors. Thanks in advance for the help!

Upvotes: 2

Views: 986

Answers (1)

robx
robx

Reputation: 2329

There is a hacky solution, making use of the fact that you can keep writing to a http.ResponseWriter after http.FileServer has done its work. Not recommended in general, but in this situation it might be acceptable.

package main

import (
        "io"
        "log"
        "net/http"
)

const (
        link = `<link rel="stylesheet" href="/path/to/style.css">`
)

func main() {
        fs := http.FileServer(http.Dir("/tmp"))
        var handler http.HandlerFunc
        handler = func(w http.ResponseWriter, r *http.Request) {
                var (
                        url   = r.URL.Path
                        isDir = url[len(url)-1] == '/'
                )
                fs.ServeHTTP(w, r)
                if isDir {
                        io.WriteString(w, link)
                }
        }
        log.Fatal(http.ListenAndServe(":8080", handler))
}

Upvotes: 2

Related Questions