// getVars returns list of variables defined in a text file and actual file // content following the variables declaration. Header is separated from // content by an empty line. Header is in YAML // If no empty newline is found - file is treated as content-only. package main import ( "fmt" "os" "path/filepath" "strings" "gopkg.in/yaml.v3" ) func getVars(path string, globals Vars) (Vars, string, error) { b, err := os.ReadFile(path) if err != nil { return nil, "", err } s := string(b) // Pick some default values for content-dependent variables v := Vars{} title := strings.Replace(strings.Replace(path, "_", " ", -1), "-", " ", -1) v["title"] = strings.ToTitle(title) v["description"] = "" v["file"] = path v["url"] = path[:len(path)-len(filepath.Ext(path))] + ".html" v["output"] = filepath.Join(PUBDIR, v["url"]) // Override default values with globals for name, value := range globals { v[name] = value } // Add a layout if none is specified // For this to work, the layout must be available // in AYADIR if _, ok := v["layout"]; !ok { v["layout"] = "layout.html" } delim := "\n---\n" if sep := strings.Index(s, delim); sep == -1 { return v, s, nil } else { header := s[:sep] body := s[sep+len(delim):] vars := Vars{} if err := yaml.Unmarshal([]byte(header), &vars); err != nil { fmt.Println("ERROR: Failed to parse header", err) return nil, "", err } else { // Override default values and globals with the ones defined in the file for key, value := range vars { v[key] = value } } if strings.HasPrefix(v["url"], "./") { v["url"] = v["url"][2:] } return v, body, nil } }