将嵌入文件呈现为文件名是可能的吗?

huangapple go评论84阅读模式
英文:

Is it possible to present an embedded file as a filename?

问题

我使用一个需要**文件名作为参数(类型为string)**的函数。当提供文件名时,它可以正常工作。

我想要将这个文件嵌入到我的二进制文件中。然后我可以将其内容作为[]bytestring,但这并不实用。我也可以将其保存为embed.FS,但我理解这是一个只能被某些函数使用的抽象。

我需要的是能够将这个嵌入的文件呈现为文件名(一个string),然后由底层函数来打开(嵌入的)文件。

这种做法可行吗?

英文:

I use a function that requires a filename as a parameter (of type string). It works fine when providing the filename.

I would like to embed this file in my binary. I can then have the contents as []byte or string but that's not useful. I can also fave it as embed.FS but my understanding is that this is an abstraction that can be used by some functions only.

What I would need is the ability to present this embedded file as a filename (a string) that would then be used by the underlying function to open the (embedded) file.

Is this possible?

答案1

得分: 3

Filename that Key accept as string argument is only abstraction on ioutil.ReadFile, see auth.go

What you can do is implement ssh.Auth yourself, here is small example.

package main

import (
	_ "embed"
	"fmt"

	"github.com/melbahja/goph"
	"golang.org/x/crypto/ssh"
)

//go:embed id_rsa
var privateKey []byte

func main() {
	auth, err := Auth(privateKey, []byte("foobar"))

	fmt.Println(auth, err)
}

func Auth(privateKey, pass []byte) (goph.Auth, error) {
	signer, err := Singer(privateKey, pass)
	if err != nil {
		return nil, err
	}

	return goph.Auth{
		ssh.PublicKeys(signer),
	}, nil
}

func Singer(privateKey, pass []byte) (ssh.Signer, error) {
	if len(pass) != 0 {
		return ssh.ParsePrivateKeyWithPassphrase(privateKey, pass)
	}
	return ssh.ParsePrivateKey(privateKey)
}
英文:

Filename that Key accept as string argument is only abstraction on ioutil.ReadFile, see auth.go

What you can do is implement ssh.Auth yourself, here is small example.

package main

import (
	_ "embed"
	"fmt"

	"github.com/melbahja/goph"
	"golang.org/x/crypto/ssh"
)

//go:embed id_rsa
var privateKey []byte

func main() {
	auth, err := Auth(privateKey, []byte("foobar"))

	fmt.Println(auth, err)
}

func Auth(privateKey, pass []byte) (goph.Auth, error) {
	signer, err := Singer(privateKey, pass)
	if err != nil {
		return nil, err
	}

	return goph.Auth{
		ssh.PublicKeys(signer),
	}, nil
}

func Singer(privateKey, pass []byte) (ssh.Signer, error) {
	if len(pass) != 0 {
		return ssh.ParsePrivateKeyWithPassphrase(privateKey, pass)
	}
	return ssh.ParsePrivateKey(privateKey)
}

huangapple
  • 本文由 发表于 2021年8月18日 20:36:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/68832541.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定