当前位置:网站首页>Golang:go静态文件处理
Golang:go静态文件处理
2022-08-01 06:50:00 【ZzzWClock】
go静态文件处理
一.前言
golang在没有处理静态文件前是访问不到的,必须用到net/http包下的
http.Handle(),http.StripPrefix(),http.FileServer(),http.Dir()
二.示例
- http.StripPrefix 会截取输入的前缀,http.FileServer 会自动在目录里面寻找文件,配合http.Dir使用
package main
import (
"fmt"
"html/template"
"net/http"
)
// html处理器
func htmlHandle(w http.ResponseWriter, r *http.Request) {
// 解析一个模版文件
// Must函数用于包装返回(*Template, error)的函数/方法调用,它会在err非nil时panic,一般用于变量初始化:
// ParseFiles函数创建一个模板并解析filenames指定的文件里的模板定义。返回的模板的名字是第一个文件的文件名(不含扩展名),内容为解析后的第一个文件的内容。至少要提供一个文件。如果发生错误,会停止解析并返回nil。
t := template.Must(template.ParseFiles("index.html"))
// Execute方法将解析好的模板应用到data上,并将输出写入wr。如果执行时出现错误,会停止执行,但有可能已经写入wr部分数据。模板可以安全的并发执行。
t.Execute(w, "我是被传递的一段话")
}
func main() {
// 路由器
http.HandleFunc("/", handle)
http.HandleFunc("/html", htmlHandle)
// 静态文件处理器
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
// 开启server服务
http.ListenAndServe(":8081", nil)
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="/static/css/layui.css">
<script src="/static/js/layui.js"></script>
</head>
<body>
<p style="color: red;">我是一个模版文件:{
{.}}</p>
<div>
<img src="/static/image/docker.png" alt="图片" style="width: 200px;">
</div>
</body>
</html>
- 访问正常
边栏推荐
- LeetCode 0150. Reverse Polish Expression Evaluation
- 05-SDRAM: Arbitration
- Matlab simulink particle swarm optimization fuzzy pid control motor pump
- 特别数的和
- Create, modify and delete tables
- 2022.7.26 模拟赛
- Speed up your programs with bitwise operations
- leetcode43 string multiplication
- MATLAB program design and application of MATLAB 2.5
- The Bean's life cycle
猜你喜欢
随机推荐
字符中的第一个唯一字符
基于百度OCR的网站验证码在线识别
仿牛客网项目总结
JSON 与 JS 对象的区别
Datagrip error "The specified database userpassword combination is rejected..."Solutions
The Bean's life cycle
Dart 异常详解
datagrip 报错 “The specified database userpassword combination is rejected...”的解决方法
深度比较两个对象是否相同
安装SQL Server详细教程
LeetCode Question of the Day (309. Best Time to Buy and Sell Stock with Cooldown)
零代码网站开发利器:WordPress
mysql中添加字段的相关问题
matplotlib pyplot
爆肝3万字,最硬核丨Mysql 知识体系、命令全集 【建议收藏 】
return; represents meaning
问下 mysql向pg同步多个表的话 有什么好的方案吗?
第6章——数据库的安全性
阿里云李飞飞:中国云数据库在很多主流技术创新上已经领先国外
MATLAB程序设计与应用 2.5 MATLAB运算