Skip to content

embed: http中使用embed,取消相对路径后,路径中/需要修改为\才能读取到静态资源 #50408

@cnwangfei

Description

@cnwangfei

What version of Go are you using (go version)?

$ go 1.16.11

我是这样做的改动

HttpEmbed

package httpEmbed

import (
	"embed"
	"io/fs"
	"path"
	"path/filepath"
)

type Fs struct {
	*embed.FS        // 静态资源
	Path      string // 设置embed文件到静态资源的相对路径,也就是embed注释里的路径
}

func (f Fs) Open(name string) (fs.File, error) {
	// 拼接相对路径
	fullName := filepath.Join(f.Path, filepath.FromSlash(path.Clean("/"+name)))
	// 修改http路径中的\为/
	fullName = filepath.ToSlash(fullName)
	//fmt.Println(fullName)
	fs, err := f.FS.Open(fullName)
	return fs, err
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions