登录
首页 >  Golang >  Go问答

使用 GOLANG 的 http.FileServer 来加载特定模板目录中的 html 文件的方法

来源:stackoverflow

时间:2024-02-15 09:27:21 472浏览 收藏

哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《使用 GOLANG 的 http.FileServer 来加载特定模板目录中的 html 文件的方法》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!

问题内容

func main() {
    mux := http.NewServeMux()
    staticHandler := http.FileServer(http.Dir("./templates"))
    mux.Handle("/", http.StripPrefix("/", staticHandler))
    log.Fatal(http.ListenAndServe(":8080", mux))
}

我想加载“templates”目录中的 html 文件。 如果“模板”中有多个文件,如何选择加载某个文件?


正确答案


您可以使用http.servefile()构建您自己的文件服务器。

参见下面的草图。

然后您可以在自定义 filehandler.servehttp() 中拦截所提供的文件。

package main

import (
    "log"
    "net/http"
    "path"
    "path/filepath"
    "strings"
)

func main() {
    mux := http.NewServeMux()

    //staticHandler := http.FileServer(http.Dir("./templates"))
    staticHandler := fileServer("./templates")

    mux.Handle("/", http.StripPrefix("/", staticHandler))
    log.Printf("listening")
    log.Fatal(http.ListenAndServe(":8080", mux))
}

// returns custom file server
func fileServer(root string) http.Handler {
    return &fileHandler{root}
}

// custom file server
type fileHandler struct {
    root string
}

func (f *fileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    upath := r.URL.Path
    if !strings.HasPrefix(upath, "/") {
        upath = "/" + upath
        r.URL.Path = upath
    }
    name := filepath.Join(f.root, path.Clean(upath))
    log.Printf("fileHandler.ServeHTTP: path=%s", name)
    http.ServeFile(w, r, name)
}

到这里,我们也就讲完了《使用 GOLANG 的 http.FileServer 来加载特定模板目录中的 html 文件的方法》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>