美文网首页
go 打包静态文件

go 打包静态文件

作者: vins | 来源:发表于2023-11-03 10:30 被阅读0次
package main

import (
    "embed"
    "html/template"
    "log"
    "net/http"
)

//go:embed templates/*.html
var templates embed.FS

//go:embed static/*
var staticFiles embed.FS

func main() {
    http.HandleFunc("/", index)
    http.Handle("/static/", http.FileServer(http.FS(staticFiles)))
    if err := http.ListenAndServe(":9090", nil); err != nil {
        log.Fatal(err)
    }
}

func index(w http.ResponseWriter, r *http.Request) {
    tmpl, err := template.ParseFS(templates, "templates/*.html")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    if err := tmpl.ExecuteTemplate(w, "index.html", nil); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
}

image.png

相关文章

网友评论

      本文标题:go 打包静态文件

      本文链接:https://www.haomeiwen.com/subject/mgkoidtx.html