go语言html css,go 1.16 embed 实现资源文件(html, css, js等)内嵌

Golang 发布1.16,如今通过//go:embed 注解内嵌资源文件并打包到二进制文件,关于//go:embed的使用网上很多教程,我想也不需要我在此在啰嗦一遍,今天的重点:用go开发网站时候内嵌的css、html、js以及图片等资源如何内嵌和渲染到网页。

6fb9ce90fa260b68b32fa40afaf7fba5.png

含有资源文件的demo项目结构

1. 在没有//go:embed支持之前的实现serve文件的方式如下:

package main

import (

"log"

"net/http"

)

func main() {

mux := http.DefaultServeMux

mux.Handle("/web/js/", http.StripPrefix("/web/js/", http.FileServer(http.Dir("static/js/"))))

mux.Handle("/web/css/", http.StripPrefix("/web/css/", http.FileServer(http.Dir("static/css/"))))

mux.Handle("/web/img/", http.StripPrefix("/web/img/", http.FileServer(http.Dir("static/img/"))))

log.Fatal(http.ListenAndServe(":8080", mux))

}

或许: pattern和prefix的设置可以简化些,比如:

mux.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("static/js/")))),

然后URL访问也能简化成: http://localhost:8080/js/bootstrap.bundle.min.js, 但这不是重点,重点是虽然URL多了一个结点,但代码简化了很多还支持了//go:embed.

2. 在支持//go:embed之后实现方式如下:

package main

import (

"embed"

_ "embed"

"log"

"net/http"

)

//go:embed template static

var Assets embed.FS

func main() {

mux := http.DefaultServeMux

mux.Handle("/web/", AssetHandler("/web/", Assets, "./static"))

log.Fatal(http.ListenAndServe(":8080", mux))

}

测试:浏览器访问http://localhost:8080/web/js/bootstrap.bundle.min.js即可访问到对应文件,访问url一样,不同的是资源文件会在go build打包后全部内嵌。

3. 之所embed的资源文件还能被serve,多亏了AssetHandler的功劳,实现如下:

package main

import (

"embed"

"io/fs"

"net/http"

"path"

)

type fsFunc func(name string) (fs.File, error)

func (f fsFunc) Open(name string) (fs.File, error) {

return f(name)

}

// AssetHandler returns an http.Handler that will serve files from

// the Assets embed.FS. When locating a file, it will strip the given

// prefix from the request and prepend the root to the filesystem.

func AssetHandler(prefix string, assets embed.FS, root string) http.Handler {

handler := fsFunc(func(name string) (fs.File, error) {

assetPath := path.Join(root, name)

// If we can't find the asset, fs can handle the error

file, err := assets.Open(assetPath)

if err != nil {

return nil, err

}

// Otherwise assume this is a legitimate request routed correctly

return file, err

})

return http.StripPrefix(prefix, http.FileServer(http.FS(handler)))

}

有疑问加站长微信联系(非本文作者)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值