首页 > 解决方案 > 使用 HandleFunc 提供通过模板链接的 CSS 文件

问题描述

我最近没有看到关于这个的问题,我很困惑。截至目前,我正在使用 HandleFunc 和模板将文件提供给谷歌云。我是一名刚毕业的学生,​​还没有使用过大量的 Golang,但我想边走边熟悉它。使用其他指南、问题和视频,我已成功地将我的 html 文件提供给服务器,并且能够显示标题。我正在使用存储在我的模板目录中的 header.html 模板,该模板链接到我的 css 目录中的 main.css。然后,我在我目前用作主要的 html 文件上使用标题模板。我无法获得我想要使用的 css 或图像。我的猜测是我需要在我的 main.go 文件中编写更多内容。我尝试使用 Handle、Handler 和 HandleFunc 以多种方式处理它,

文件结构:

├── 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
}

电子邮件列表.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}}

对不起所有的代码,但我真的很难过。如何让我的 css 和图像文件与 emailList.html 一起使用?先感谢您!!

与@Mayank 解决方案类似,答案是:

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

标签: htmlcssgogoogle-cloud-platformhttphandler

解决方案


要提供静态文件,您应该FileServer使用 http 包的方法。尝试将主要功能代码更改为类似

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

推荐阅读