Skip to content

Instantly share code, notes, and snippets.

@dariodip
Last active March 30, 2021 20:50
Show Gist options
  • Save dariodip/96dc0c17eb5e7f6b3e9fa37fac976308 to your computer and use it in GitHub Desktop.
Save dariodip/96dc0c17eb5e7f6b3e9fa37fac976308 to your computer and use it in GitHub Desktop.
Go embed
import (
"crypto/md5"
"crypto/sha256"
"fmt"
"io"
)
// ComplexStruct stores a value and its MD5 and SHA256 ingests
type ComplexStruct struct {
Value string
MD5Ingest []byte
SHA256Ingest []byte
}
func NewComplexStruct(v string) ComplexStruct {
md5h := md5.New()
io.WriteString(md5h, v)
sha256h := sha256.New()
io.WriteString(sha256h, v)
return ComplexStruct{
Value: v,
MD5Ingest: md5h.Sum(nil),
SHA256Ingest: sha256h.Sum(nil),
}
}
func (cs ComplexStruct) String() string {
return fmt.Sprintf("v=%s,md5=%x,sha256=%x",
cs.Value,
cs.MD5Ingest,
cs.SHA256Ingest,
)
}
//go:embed complex_structures.gob
var embedCs []byte
func main() {
var complexStructures []ComplexStruct
decoder := gob.NewDecoder(bytes.NewReader(embedCs))
if err := decoder.Decode(&complexStructures); err != nil {
panic(err)
}
for _, cs := range complexStructures {
fmt.Println(cs)
}
}
func encode(complexStructures []ComplexStruct) {
var buf bytes.Buffer
encoder := gob.NewEncoder(&buf)
if err := encoder.Encode(&complexStructures); err != nil {
panic(err)
}
// this is just an example! never write a file inside a function that way
if err := os.WriteFile("complex_structures.gob", buf.Bytes(), os.ModePerm); err != nil {
panic(err)
}
}
import (
"embed"
"fmt"
"io/ioutil"
)
//go:embed *
var fs embed.FS
func main() {
files, _ := fs.ReadDir(".")
for _, file := range files {
fmt.Println("File name: ", file.Name())
fileContent, _ := fs.Open(file.Name())
content, _ := ioutil.ReadAll(fileContent)
fmt.Println("File content:\n", string(content))
}
}
import (
_ "embed"
"fmt"
)
//go:embed hello.txt
var hello []byte
func main() {
fmt.Println(string(hello))
}
Hello from embedded!
import (
_ "embed"
"fmt"
)
//go:embed hello.txt
var hello string
func main() {
fmt.Println(hello)
}
import (
"embed"
"fmt"
)
//go:embed *
var f embed.FS
func main() {
data, _ := f.ReadFile("hello.txt")
fmt.Println(string(data))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment