go 打包静态文件

2023-11-03  本文已影响0人  vins
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
上一篇 下一篇

猜你喜欢

热点阅读