htmlcssgogoogle-cloud-platformhttphandler

Using HandleFunc to serve CSS file linked through template


I haven't seen a recent question about this, and I am stumped. As of now I am using HandleFunc and templates to serve files to google cloud. I am a recent graduate and have not used a ton of Golang, but I wanted to familiarize myself with it as I go. Using other guides, questions, and videos I have successfully served my html files to the server and was able to get a header displayed. I am using a header.html template stored in my templates directory which links to main.css in my css directory. I then use the header template on my html file that I am using as main at the moment. I cannot get the css or the image I want to use to work. My guess is that I need to write more in my main.go file.. I tried handling it multiple ways using Handle, Handler, and HandleFunc, and I admit I am still am a little rough understanding how those functions work and differ, but I cannot understand what is causing the issue for me.

File Structure:

├── app.yaml
├── main.go
└── static
    ├── css
    │   └── main.css
    ├── emailList.html
    ├── img
    │   ├── TheBuzzTraders.png
    │   ├── favicon.ico
    │   └── tbtWordLogo.png
    ├── js
    └── templates
        └── header.html

main.go:

package main

import (
    "fmt"
    "html/template"
    "net/http"
    "os"
    "path/filepath"
    "strings"
)

func emailListHandler(w http.ResponseWriter, r *http.Request) {
    tpl.ExecuteTemplate(w, "emailList", &Page{Title: "Welcome to my site"})
}

func main() {
    http.HandleFunc("/", emailListHandler)
    fmt.Println(http.ListenAndServe(":8080", nil))
}

var tpl = func() *template.Template {
    t := template.New("")
    err := filepath.Walk("./", func(path string, info os.FileInfo, err error) error {
        if strings.Contains(path, ".html") {
            fmt.Println(path)
            _, err = t.ParseFiles(path)
            if err != nil {
                fmt.Println(err)
            }
        }
        return err
    })

    if err != nil {
        panic(err)
    }
    return t
}()

type Page struct {
    Title string
}

emailList.html:

{{define "emailList"}}
<!DOCTYPE html>
<html lang="en">
    {{template "header" .}}
    <body>
        <h1>Invest in your tomorrow</h1>

        <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
    </body>
</html>
{{end}}

header.html:

{{define "header"}}
<head>
    <!-- Bootstrap and CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="../css/main.css">

    <meta charset="UTF-8">
    <title>The Buzz Traders</title>
</head>
{{end}}

Sorry for all the code, but I really am stumped. How do I get my css, and image files to work with emailList.html? Thank you in advance!!

Similarly to @Mayank solution, the answer was:

    http.HandleFunc("/", emailListHandler)
    fs := http.FileServer(http.Dir("static"))
    http.Handle("/css/", fs)
    http.Handle("/img/", fs)
    http.Handle("/templates/", fs)
    fmt.Println(http.ListenAndServe(":8080", nil))
}```

Solution

  • To serve static files, you should FileServer method of http package. Try changing the main function code to something like

    func main() {
        http.HandleFunc("/", emailListHandler)
        fs := http.FileServer(http.Dir("./static"))
        http.Handle("/", fs)
        fmt.Println(http.ListenAndServe(":8080", nil))
    }