关于go:使用embed在go中嵌入静态htmljscss文件

29次阅读

共计 1341 个字符,预计需要花费 4 分钟才能阅读完成。

前言

在 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 文件是否被正确援用

正文完
 0