介绍本文沿用以上(GolangGinWeb框架6-绑定请求字符串/URI/请求头/复选框/表单类型)继续探索GinWeb框架静态文件服务包mainimport("github.com/gin-gonic/gin""log""net/http""os")funcmain(){router:=gin.Default()cwd,_:=os.Getwd()//获取当前文件目录log.Printf("当前项目路径:%s",cwd)router.Static("/static",cwd)//提供静态文件服务器,第一个参数是相对路径,第二个参数是根路径,这个路径一般放css等静态文件,js、字体等,前端html使用/static/js/xxx或/static/css/xxx等相对路径引用router.StaticFS("/more_static",http.Dir("./"))//本地文件树结构映射到前端,可以通过浏览器访问本地文件系统,模拟访问:http://localhost:8080/more_staticrouter.StaticFile("/logo.png","./resources/logo.png")//StaticFile提供单一的Staticsingle-file服务,模拟访问:http://localhost:8080/log.png//Listenandserveon0.0.0.0:8080router.Run(":8080")}returnsfiledatapackagemainimport("github.com/gin-contrib/cors""github.com/gin-gonic/gin""net/http")funcmain(){router:=gin.Default()router.Use(cors.Default())router.GET("/local/文件”,函数(c*gin.Context){c.File("./main.go")})//AFileSystem实现对命名文件集合的访问。//文件路径中的元素由斜线分隔('/',U+002F)//字符,与主机操作系统约定无关。//文件系统接口,需要实现thefile访问方式,提供文件访问服务根路径的HTTP处理器varfshttp.FileSystem=http.Dir("./")//使用本地目录作为文件服务根路径router.GET("/fs/file",func(c*gin.Context){c.FileFromFS("main.go",fs)//返回文件服务系统下的文件数据})router.Run(":8080")}/*模拟访问文件数据:curlhttp://localhost:8080/local/file模拟文件系统下访问文件数据:curlhttp://localhost:8080/fs/file*/使用文件阅读器提供文件数据服务packagemainimport("github.com/gin-gonic/gin""net/http")funcmain(){router:=gin.Default()router.GET("/someDataFromReader",func(c*gin.Context){response,err:=http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png")iferr!=nil||response.StatusCode!=http.StatusOK{//当请求链接中的文件有错误时,直接返回服务不可用c.Status(http.StatusServiceUnavailable)return}readr:=response.Body//用响应体的内容构造一个文件阅读器deferreader.Close()contentLength:=response.ContentLengthcontentType:=response.Header.Get("Content-Type")extraHeaders:=map[string]string{"Content-Disposition":`attachment;filename="gopher.png"`,}//DataFromReader将指定的reader写入bodystream并更新HTTP代码。//func(c*Context)DataFromReader(codeint,contentLengthint64,contentTypestring,readerio.Reader,extraHeadersmap[string]string){}//DataFromReader方法将指定reader的内容写入http响应体流,并更新响应码、响应头信息等c.DataFromReader(http.StatusOK,contentLength,contentType,reader,extraHeaders)})router.Run(":8080")}/*模拟访问:curlhttp://localhost:8080/someDataFromReader*/HTML渲染使用LoadHTMLGlob()方法或LoadHTMLFiles()方法packagemainimport("github.com/gin-gonic/gin""net/http")funcmain(){router:=gin.Default()//LoadHTMLGlob方法加载s以glob模式匹配HTML文件,并将其与HTML渲染器组合router.LoadHTMLGlob("templates/*")//router.LoadHTMLFiles("templates/template1.html","templates/template2.html")router.GET("/index",func(c*gin.Context){//设置响应码、模板文件名、渲染替换的HTML方法模板值,设置响应内容类型Content-Type"text/html"c.HTML(http.StatusOK,"index.tmpl",gin.H{"title":"Mainwebsite",})})router.Run(":8080")}/*模拟测试:curlhttp://localhost:8080/index*/添加模板文件,templates/index.tmpl
{{.title}}
/html>在不同的文件夹中使用相同文件名的模板文件funcmain(){router:=gin.Default()router.LoadHTMLGlob("templates/**/*")router.GET("/posts/index",func(c*gin.Context){c.HTML(http.StatusOK,"posts/index.tmpl",gin.H{"title":"Posts",})})router.GET("/users/index",func(c*gin.Context){c.HTML(http.StatusOK,"users/index.tmpl",gin.H{"title":"Users",})})router.Run(":8080")}在posts目录下添加模板文件,templates/posts/index.tmpl{{define"posts/index.tmpl"}}{{.title}}
使用posts/index.tmpl
在{{end}}users目录下添加模板文件,templates/users/index.tmpl{{define"users/index.tmpl"}}{{.title}}
Usingusers/index.tmpl
{{end}}自定义模板渲染你也可以使用自定义HTML模板渲染器,你需要自定义模板文件file1、file2等。=gin.Default()//template.ParseFiles(file1,file2...)创建一个模板对象,然后解析一组模板,使用文件名作为模板的名称//Must方法将模板和error为换行,返回模板的内存地址一般用于变量初始化,如:vart=template.Must(template.New("name").Parse("html"))html:=template.Must(template.ParseFiles("file1","file2"))router.SetHTMLTemplate(html)//关联模板和HTML渲染器router.GET("/index",func(c*gin.Context){//HTML方法设置响应se代码,模板文件名,渲染替换模板中的值,设置响应内容类型Content-Type"text/html"c.HTML(http.StatusOK,"file1",gin.H{"title":"主网站",})})router.Run(":8080")}自定义分隔符可以自定义分隔符,模板中默认的分隔符是{{}},我们也可以修改,比如加一对中括号r:=gin.Default()r.Delims("{[{","}]}")r.LoadHTMLGlob("/path/to/templates")示例代码中有详细的自定义模板方法。模板和后端都定义了好的模板方法,该方法在模板渲染时执行,类似于filter方法,比如时间格式化操作packagemainimport("fmt""html/template""net/http""time""github.com/gin-gonic/gin")funcformatAsDate(ttime.Time)string{year,month,day:=t.Date()//日期方法返回年月日returnfmt.Sprintf("%d%02d/%02d",year,month,day)//格式化时间}funcmain(){router:=gin.Default()router.Delims("{[{","}]}")//左边和自定义模板中的右分隔符//SetFuncMap方法使用Gin引擎上设置给定的template.FuncMap,后面渲染模板时会调用同名方法//FuncMap是一个map,keyname与方法名相关联,键值与方法相关联。每个方法必须返回一个值,或者返回两个值,其中第二个是错误类型")//加载单个模板文件并与HTMLRenderer关联比较router.GET("/raw",func(c*gin.Context){c.HTML(http.StatusOK,"raw.tmpl",gin.H{"now":time.Date(2017,07,01,0,0,0,0,time.UTC),})})router.Run(":8080")}/*模拟测试:curlhttp://localhost:8080/raw*/定义模板文件:raw.tmplDate:{[{.now|formatAsDate}]}时间格式结果:Date:2017/07/01Gin使用的模板默认只有一个html.Template模板引擎,也可以参考多模板渲染器使用类似于Go1.6的块模板功能。关于模板的详细介绍请参考官方模板包参考文档Gin官方仓库:https://github.com/gin-gonic/gin