MCPcopy
hub / github.com/OpenNHP/opennhp / LoadFilesRecursively

Function LoadFilesRecursively

endpoints/server/httpserver.go:161–201  ·  view source on GitHub ↗

LoadFilesRecursively loads HTML and template files recursively from the specified directory and adds them to the given gin.Engine. It walks through the directory and its subdirectories, and for each file with a .html or .tmpl extension, it reads the file content, creates a new template with the file

(g *gin.Engine, dir string)

Source from the content-addressed store, hash-verified

159// The directory path should be a clean absolute path.
160// If any error occurs during the file loading or template parsing, the function returns the error.
161func LoadFilesRecursively(g *gin.Engine, dir string) {
162 _, err := os.Stat(dir)
163 if os.IsNotExist(err) {
164 // dir does not exist
165 return
166 }
167
168 cleanRootDir := filepath.Clean(dir)
169 rootTmpl := template.New("").Funcs(g.FuncMap)
170 f := os.DirFS(cleanRootDir)
171
172 err = fs.WalkDir(f, ".", func(path string, info fs.DirEntry, walkErr error) error {
173 // add *.html and *.tmpl files
174 if !info.IsDir() && (strings.HasSuffix(path, ".html") || strings.HasSuffix(path, ".tmpl")) {
175 if walkErr != nil {
176 return walkErr
177 }
178
179 absPath := filepath.Join(cleanRootDir, path)
180 content, err := os.ReadFile(absPath)
181 if err != nil {
182 return err
183 }
184
185 t := rootTmpl.New(path) // template name is relative path separated by slash on all platforms
186 _, err = t.Parse(string(content))
187 if err != nil {
188 return err
189 }
190 log.Info("gin load file %s from %s", path, cleanRootDir)
191 g.SetHTMLTemplate(t)
192 }
193
194 return nil
195 })
196
197 if err != nil {
198 log.Error("load files to web engine failed. %v", err)
199 return
200 }
201}
202
203// init gin engine. Must be called at initialization
204func (hs *HttpServer) initRouter() {

Callers 1

initRouterMethod · 0.85

Calls 1

ErrorMethod · 0.65

Tested by

no test coverage detected