Utilizzo di HandleFunc per servire file CSS collegati tramite modello

Aug 30 2020

Non ho visto una domanda recente su questo, e sono perplesso. A partire da ora sto usando HandleFunc e modelli per servire file su Google Cloud. Sono un neolaureato e non ho usato una tonnellata di Golang, ma volevo familiarizzare con esso mentre vado. Utilizzando altre guide, domande e video ho servito con successo i miei file html sul server e sono riuscito a visualizzare un'intestazione. Sto usando un modello header.html memorizzato nella mia directory dei modelli che si collega a main.css nella mia directory CSS. Quindi utilizzo il modello di intestazione sul mio file html che sto usando come principale al momento. Non riesco a ottenere il CSS o l'immagine che voglio usare per funzionare. La mia ipotesi è che devo scrivere di più nel mio file main.go .. Ho provato a gestirlo in più modi usando Handle, Handler e HandleFunc,

Struttura del file:

├── 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/[email protected]/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}}

Scusa per tutto il codice, ma sono davvero perplesso. Come faccio a far funzionare i miei file CSS e immagine con emailList.html? Grazie in anticipo!!

Analogamente alla soluzione @Mayank, la risposta è stata:

    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))
}```

Risposte

2 MayankPatel Aug 30 2020 at 11:00

Per servire file statici, dovresti utilizzare il FileServermetodo del pacchetto http. Prova a cambiare il codice della funzione principale in qualcosa di simile

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