Skip to content

Commit 3dafe29

Browse files
pyros2097aldas
authored andcommitted
add go1.16 embed feature recipe
1 parent c945787 commit 3dafe29

File tree

4 files changed

+58
-0
lines changed

4 files changed

+58
-0
lines changed

cookbook/embed/app/index.html

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<meta charset="utf-8">
5+
<title>go embed Example</title>
6+
<script src="/static/main.js" charset="utf-8"></script>
7+
</head>
8+
<body>
9+
<h1>go embed Example</h1>
10+
</body>
11+
</html>

cookbook/embed/app/main.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
alert("main.js");

cookbook/embed/server.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package main
2+
3+
import (
4+
"embed"
5+
"io/fs"
6+
"log"
7+
"net/http"
8+
"os"
9+
10+
"github.com/labstack/echo/v4"
11+
)
12+
13+
//go:embed app
14+
var embededFiles embed.FS
15+
16+
func getFileSystem(useOS bool) http.FileSystem {
17+
if useOS {
18+
log.Print("using live mode")
19+
return http.FS(os.DirFS("app"))
20+
}
21+
22+
log.Print("using embed mode")
23+
fsys, err := fs.Sub(embededFiles, "app")
24+
if err != nil {
25+
panic(err)
26+
}
27+
28+
return http.FS(fsys)
29+
}
30+
31+
func main() {
32+
e := echo.New()
33+
useOS := len(os.Args) > 1 && os.Args[1] == "live"
34+
assetHandler := http.FileServer(getFileSystem(useOS))
35+
e.GET("/", echo.WrapHandler(assetHandler))
36+
e.GET("/static/*", echo.WrapHandler(http.StripPrefix("/static/", assetHandler)))
37+
e.Logger.Fatal(e.Start(":1323"))
38+
}

website/content/cookbook/embed-resources.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,14 @@ description = "Embed resources recipe for Echo"
1414

1515
## [Source Code]({{< source "embed-resources" >}})
1616

17+
## With go 1.16 embed feature
18+
19+
`server.go`
20+
21+
{{< embed "embed/server.go" >}}
22+
23+
## [Source Code]({{< source "embed" >}})
24+
1725
## Maintainers
1826

1927
- [caarlos0](https://github.com/caarlos0)

0 commit comments

Comments
 (0)