当前位置:网站首页>Golang: go static file processing
Golang: go static file processing
2022-08-01 07:04:00 【ZzzW Clock】
go静态文件处理
一.前言
golangIt is not accessible until static files are processed,必须用到net/http包下的
http.Handle(),http.StripPrefix(),http.FileServer(),http.Dir()
二.示例
- http.StripPrefix will intercept the input prefix,http.FileServer It will automatically look for files in the directory,配合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>
- 访问正常
边栏推荐
- flinkcdc对mysql的date字段类型转化有什么解决思路么
- ORACLE modify another user package (package)
- Using FiddlerScript caught poly FiddlerScript 】 【 download
- 零代码网站开发利器:WordPress
- LeetCode240+312+394
- Motion analysis and parameter optimization of crank-slider mechanism
- 从底层结构开始学习FPGA(6)----分布式RAM(DRAM,Distributed RAM)
- 响应式织梦模板园林花卉类网站
- 仿牛客网项目总结
- 从离线到实时对客,湖仓一体释放全量数据价值
猜你喜欢
基于MATLAB的BP神经网络进行语音特征信号分类
电磁兼容简明教程(6)测试项目
Dell PowerEdge Server R450 RAID Configuration Steps
datagrip 报错 “The specified database userpassword combination is rejected...”的解决方法
太厉害了,终于有人能把文件上传漏洞讲的明明白白了
Practical training Navicat Chinese and English mode switching
Vim简介
MATLAB程序设计与应用 2.5 MATLAB运算
曲柄滑块机构运动分析和参数优化
crypto-js uses
随机推荐
「面经分享」西北大学 | 字节 生活服务 | 一面二面三面 HR 面
戴尔PowerEdge服务器R450 RAID配置步骤
从零开始—仿牛客网讨论社区项目(一)
leetcode125 Verify palindrome string
小白的0基础教程SQL: 安装MYSQL 03
声音信号处理基频检测和时频分析
问下 mysql向pg同步多个表的话 有什么好的方案吗?
2022.7.27 Selected lectures on good topics
Self-made a remote control software - VeryControl
图片无损压缩软件哪个好用:试试完全免费的JPG-C 图片批量修整压缩减肥工具吧 | 最新jpg批量修整工具下载
Vim简介
Motion analysis and parameter optimization of crank-slider mechanism
Vim三种模式
JVM: Runtime Data Area - PC Register (Program Counter)
NUMPY
LeetCode240+312+394
my creative day
MVVM project development (commodity management system 1)
测试工具(四)Jenkins环境搭建与使用
Talk about the bugs in using for in to traverse the array in js