With the new embed package, I was able to embed my files, and call my templates as below:
// inner/embed.go
package inner
import (
"embed"
)
// Content is our static web server content.
//go:embed configuration template layout
var Content embed.FS // files with names beginning with ‘.’ or ‘_’ are excluded
// web/Bayan.go
package web
import (
"fmt"
"hasan/embed/inner"
"html/template"
"log"
"net/http"
"os"
"gopkg.in/yaml.v2"
)
// Config ...
type Config struct {
Server struct {
Port string `yaml:"port"`
Host string `yaml:"host"`
} `yaml:"server"`
Database struct {
Username string `yaml:"user"`
Password string `yaml:"pass"`
} `yaml:"database"`
}
func processError(err error) {
fmt.Println(err)
os.Exit(2)
}
func readFile(cfg *Config, lang string) {
data, err := inner.Content.ReadFile("configuration/bayan-" + lang + ".yml")
if err != nil {
log.Fatal(err)
}
// fmt.Println(string(data))
err = yaml.Unmarshal([]byte(data), &cfg)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("%+v\n", cfg)
fmt.Printf("%+v\n", cfg.Database.Username)
}
// Bayan ...
func Bayan(w http.ResponseWriter, r *http.Request) {
var cfg Config
var lng string
lang, err := r.Cookie("language")
if err != nil {
lng = "ar"
} else {
lng = lang.Value
}
readFile(&cfg, lng)
var tmpl *template.Template
tmpl, err = template.ParseFS(inner.Content, "layout/layout.html", fmt.Sprint("template/bayan-", lng, ".html"))
if err != nil {
fmt.Println(err)
}
//tmpl, err := template.New("").ParseFiles(fmt.Sprint("template/bayan-en.html"), "base.html")
//tmpl, err := template.ParseFiles(fmt.Sprint(http.FS(inner.Content), "/layout/layout.html"))
// or
//tmpl := template.Must(template.ParseFiles("layout/layout.html"))
//tmpl.Execute(w, "data goes here, this is Hasan")
tmpl.ExecuteTemplate(w, "base", "hi")
if err != nil {
fmt.Println(err)
}
}
// main.go
package main
import (
"fmt"
"hasan/embed/inner"
"hasan/embed/web"
"net/http"
_ "embed"
"github.com/zserge/lorca"
)
func main() {
port := "8090"
go func() {
http.HandleFunc("/bayan", web.Bayan)
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(inner.Content))))
http.ListenAndServe(":"+port, nil)
}()
// Start UI
ui, err := lorca.New("http://localhost:8090/bayan", "", 1200, 800)
if err != nil {
fmt.Println("error:", err)
}
defer ui.Close()
<-ui.Done()
}
And my embed files are located at folder inner
as:
My question is, how can I call JavaScript
, CSS
and img
files in the templates.
for example, how can I replace the <link href="/styles/fontawesome-free-5.15.2-web/css/all.css" rel="stylesheet">
in the templates now?