gogorillago-http

Prepoluting index page before mux Handle call


I recently built a small blog website for testing purposes and I'm a little stuck with this problem while writing the server in Go. I have all the files of the website inside the static folder, which is also the root for the http.FileServer given to mux.Handle. Everything works fine, except that I need to pre-polutate the data of the index page with the data of the articles.

If I build the index page with mux.HandleFunc and call the index that way I lose all the CSS format because, of course, mux does not know where to find that since he has no root fs to check into.

So my question basically is: is it possible to pre-populate the index page with some data (e.g. reading the data from a json file and parse it with template.ParseFiles, for example) and still use mux.Handle as mount point of the website?

package main

import (
    "mywebsite/handlers"
    "net/http"
)

func main() {

    var mux = http.NewServeMux()
    mux.Handle("/", http.FileServer(http.Dir("static")))

    /*This throws panic: pattern "/" (registered at /home/nicola/Desktop/mywebsite/main.go:12) conflicts with pattern "/" (registered at /home/nicola/Desktop/mywebsite/main.go:11):
    / matches the same requests as / */
    mux.HandleFunc("/", handlers.IndexHandler)

    err := http.ListenAndServe(":3345", mux)
    if err != nil {
        panic(err)
    }
}

Thank you so much for any hint!


Solution

  • I somehow solved like this. Moved css into a separate directory called css. So basically my workspace is now something like this:

    .
    ├── blogposts
    │   ├── 1.html
    │   └── 2.html
    ├── go.mod
    ├── handlers
    │   ├── contactshandler.go
    │   ├── indexhandler.go
    │   ├── projectshandler.go
    │   └── readerhandler.go
    ├── main.go
    └── static
        ├── components
        │   ├── navigation-links1.css
        │   └── navigation-links1.html
        ├── contacts.html
        ├── css
        │   ├── 404.css
        │   ├── contacts.css
        │   ├── index.css
        │   ├── projects.css
        │   └── style.css
        ├── index.html
        ├── package.json
        ├── projects.html
        └── public
            └── external
                ├── 1f3eb.svg
                └── 1f44b.svg
    

    Then routed the mux like this

        mux.Handle("/css/", http.FileServer(http.Dir("static")))
        mux.Handle("/components/", http.FileServer(http.Dir("static")))
        mux.Handle("/public/external/", http.FileServer(http.Dir("static")))
        
        mux.HandleFunc("/", handlers.IndexHandler)
        mux.HandleFunc("/projects", handlers.ProjectsHandler)
        mux.HandleFunc("/contacts", handlers.ContactsHandler)
        mux.HandleFunc("/read/", handlers.ReaderHandler)
    

    So basically mux now handles three different fs, one for each folder inside static serving CSS and other graphic stuff. Not the most beautiful job, but for this little website it works fine!