前言

在Go语言中,可以使用embed包嵌入静态文件。embed包是Go 1.16版本引入的特性,它支持将静态文件打包到可执行程序中,这样就不必外部依赖资源文件了。

用处举例:go结合html打包桌面应用

用法

1.文件目录:

|- main.go
|- web
    |- index.html
    |- assets
        |- index.js
        |- index.css

2.go文件

package main

import (
    "embed"
    "fmt"
    "net/http"
)

//go:embed web/index.html
var staticFiles embed.FS

//go:embed web/assets/*
var assetsFiles embed.FS

func main() {
    http.HandleFunc("/", serveIndex)
    files, err := assetsFiles.ReadDir("web/assets")
    if err != nil {
        panic(err)
    }
    for _, file := range files {
        fileName := file.Name()
        fmt.Println("/assets/" + fileName)
        http.HandleFunc("/assets/"+fileName, handleAssets(fileName))
    }

    fmt.Println("Listen:8080...")
    err = http.ListenAndServe(":8080", nil)
    if err != nil {
        fmt.Println(err.Error())
    }
}

func serveIndex(w http.ResponseWriter, r *http.Request) {
    indexHTML, err := staticFiles.ReadFile("web/index.html")
    if err != nil {
        http.Error(w, "404 Not Found", http.StatusNotFound)
        return
    }
    fmt.Fprintf(w, string(indexHTML))
}

func serveStatic(w http.ResponseWriter, r *http.Request) {
    staticServer := http.FileServer(http.FS(assetsFiles))
    http.StripPrefix("/assets/", staticServer).ServeHTTP(w, r)
}

func handleAssets(fileName string) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        indexHTML, err := assetsFiles.ReadFile("web/assets/" + fileName)
        if err != nil {
            // http.Error(w, "404 Not Found", http.StatusNotFound)
            fmt.Println(err.Error())
            return
        }
        fmt.Fprintf(w, string(indexHTML))
    }
}

3.调试
访问:http://localhost:8080/
查看html,js,css文件是否被正确引用


IT小马
1.2k 声望166 粉丝

Php - Go - Vue - 云原生