http.FileServer静态文件服务处理器和模板引擎使用

首先它是一个处理器,其次它何以指定目录上的请求路径动态解析,读取文件流,把流转为字符串交给text/template去解析,或者读取的是有格式的html文件,交给html/template去解析,并写入响应流中,如下:

Go 复制代码
	// 访问路径http://localhost:8080/static/static/file
	// http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./public"))))
	filesHandler := http.FileServer(http.Dir("./public"))
	//路由静态文件路径上必须加上/,表示后面有动态目录下文件,加前缀在服务文件目录下查找目录和匹配文件
	http.DefaultServeMux.Handle("/static/", http.StripPrefix("/static/", filesHandler))
	// http.Handle("/", loggingHandler(http.HandlerFunc(handle))) //接收函数类型的handle的实现者,先转为函数类型在自动转为接口
	http.HandleFunc("/addCookies", addCookies)
	fmt.Println("服务已启动")
	http.ListenAndServe(":8080", nil)

如上注意点是在文件的路由地址上往往忽略掉/static/最后一个/与其他的路由地址不同,它会向后继续匹配到基础服务的文件目录,加上目录的前缀 访问文件。

模板引擎html/template和text/template的使用差不多,前者处理格式文本内容和模板语法内容结合,后者处理模板文本内容,转化显示,工作量要少一些。template.ParseFiles解析多模板,柱模版负责展示,辅助模板负责局部引入渲染,使用ts.ExecuteTemplate(w, "index", nil)时要指定核心模板,如果找不到模板名就会不处理,模板名定义在解析的渲染文件中{{define "index"}}{{end}}

如果不用模板名就使用ts.Execute(w,nil)它会加载第一个文件处理,想以模板引擎的语法引入局部的模板还是要解析到辅助模板名,这样使用方便,之间可以共享变量,否则只能像传统引入静态http文件,在统一的上下文渲染后端的值。

Go 复制代码
// 先获取请求的cookie的信息
	cookie, err := r.Cookie("firest_ck") //两种方式读一种是根据key读一个根据对象头信息直接都、读所有
	ck2 := r.Header["Cookie"]            //获取请求头的信息
	fmt.Println(ck2)
	if err == nil {
		fmt.Println(cookie)
	}

	// 创建内置的符合浏览器的cookie的结构体
	c1 := http.Cookie{Name: "first_ck", Value: "session_id:123", HttpOnly: true}
	c2 := http.Cookie{Name: "second_ck", Value: "session_id:123", HttpOnly: true}
	w.Header().Set("Set-Cookie", c1.String())
	w.Header().Add("Set-cookie", c2.String())
	http.SetCookie(w, &c1) //第二种方式设置响应体的cookie(目前响应头有三个)
	// 模板解析有两种方式1 单模板的传参解析文件2多模板多文件的解析
	// 不同点多模块模板需要严格对模块解析,单模板只需要解析
	ts := template.Must(template.ParseFiles("./public/static/index.html"))
	//指定一个核心模板其他为辅助做布局,必须提供有效模板名
	// 如果没有就用ts.Execute(w,nil)指定第一个文件为核心
	ts.ExecuteTemplate(w, "index", nil)
	// ts.Execute(w,nil)
	// http.Redirect(w, r, "http://www.baidu.com", 302) //永久重定向
相关推荐
权咚1 小时前
阿权的开发经验小集
git·ios·xcode
用户092 小时前
TipKit与CloudKit同步完全指南
ios·swift
法的空间8 小时前
Flutter JsonToDart 支持 JsonSchema
android·flutter·ios
2501_915918419 小时前
iOS 上架全流程指南 iOS 应用发布步骤、App Store 上架流程、uni-app 打包上传 ipa 与审核实战经验分享
android·ios·小程序·uni-app·cocoa·iphone·webview
00后程序员张10 小时前
iOS App 混淆与加固对比 源码混淆与ipa文件混淆的区别、iOS代码保护与应用安全场景最佳实践
android·安全·ios·小程序·uni-app·iphone·webview
ftpeak18 小时前
从零开始使用 axum-server 构建 HTTP/HTTPS 服务
网络·http·https·rust·web·web app
Magnetic_h19 小时前
【iOS】设计模式复习
笔记·学习·ios·设计模式·objective-c·cocoa
00后程序员张21 小时前
详细解析苹果iOS应用上架到App Store的完整步骤与指南
android·ios·小程序·https·uni-app·iphone·webview
前端小超超21 小时前
capacitor配置ios应用图标不同尺寸
ios·蓝桥杯·cocoa
2501_915106321 天前
Xcode 上传 ipa 全流程详解 App Store 上架流程、uni-app 生成 ipa 文件上传与审核指南
android·macos·ios·小程序·uni-app·iphone·xcode