问题

通过typescript读取本地文件会出现 allow access

思路

可以使用Go文件服务器使文件可通过http的形式访问到。

解决

// app.go
type App struct {
	ctx   context.Context
	mux   *http.ServeMux // 定义文件服务器
	paths map[string]string  // 存储路由地址
}

// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
	a.ctx = ctx
	a.mux = http.NewServeMux()
	a.mux.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("/"))))
	if err := http.ListenAndServe(":3008", a.mux); err != nil {
		log.Fatal(err)
	}
}
...

// ReadImage 读取文件
func (a *App) ReadImage(name string) string {
	p, _ := filepath.Abs(filepath.Dir(name))
	var split []string
	var pathPre string
	if strings.Contains(p, ":") {
		split = strings.Split(p, ":")

		if "" == a.paths[split[0]] {
			if nil == a.paths {
				a.paths = make(map[string]string)
			}
			a.paths[split[0]] = split[0]
			a.mux.Handle("/"+split[0]+"/", http.StripPrefix("/"+split[0]+"/", http.FileServer(http.Dir(split[0]+":"))))
		}
		pathPre = split[0] + "\\" + split[1] + "\\"
	} else {
		splits := strings.Split(p, "\\")

		split = append(split, splits[2])
		var temp string
		for _, item := range splits[4:] {
			if temp == "" {
				temp = item
			} else {
				temp = temp + "\\" + item

			}
		}
		split = append(split, temp)

		if "" == a.paths[split[0]] {
			if nil == a.paths {
				a.paths = make(map[string]string)
			}
			a.paths[split[0]] = split[0]
            // TODO 设置共享目录读取 暂时只能写死
			a.mux.Handle("/"+split[0]+"/", http.StripPrefix("/"+split[0]+"/", http.FileServer(http.Dir("\\\\x.x.x.x\\测试"))))
		}
		pathPre = split[0] + "\\" + split[1] + "\\"
	}

	log.Println(pathPre + filepath.Base(name))
	return pathPre + filepath.Base(name)
}

定义触发设置路由方法

// App.d.ts
export function ReadImage(arg1:string):Promise<string>;
// App.js
export function ReadImage(arg1) {
  return window['go']['main']['App']['ReadImage'](arg1);
}
// 定义go方法触发
runtime.EventsEmit(app.ctx, "setPhoto", strings)
// 接收触发的回调
window.runtime.EventsOn("setPhoto", function (e) {
      e.map((item) => {
    ReadImage(item).then((data) => {
      let url = "http://localhost:3008/" + data
        console.log(url)
    });
  })
})