处理动态请求
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Welcome to my website!")
})
该代码响应根链接访问,并发送数据。
提供静态资源服务
fs := http.FileServer(http.Dir("static/"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
指定一个文件夹路径后,http.FileServer可提供文件服务,用于访问指定文件夹中的文件。
接下来,指定http.FileServer响应的url,即:static。
http.StripPrefix用于裁剪url,以匹配url和文件路径的映射。
如果没有这个方法,那么有以下两种修改方式:
- 代码需要改成:
http.Handle("/", fs)
通过访问链接例如:http://localhost:8090/1.jpg,才能访问静态文件。
- static文件夹中再创建文件夹image,代码改成:
http.Handle("/image", fs)
通过访问链接例如:http://localhost:8090/image/1.jpg,才能访问静态文件。
注意,以上方法都会导致url解析混乱,不建议这样做。
接受http连接
http.ListenAndServe(":8090", nil)
该代码用于启动端口监听和http服务。
完整源码
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Welcome to my website!")
})
fs := http.FileServer(http.Dir("static/"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
http.ListenAndServe(":8090", nil)
}
准备资源文件,并放入指定文件夹中:
% tree static
static
├── 1.jpg
├── css
│ └── styles.css
└── image
└── 1.jpg
body {
background-color: black;
}
运行后,打开浏览器并输入链接:http://localhost:8090/static/css/styles.css,浏览器中显示以下内容:
body {
background-color: black;
}
本文介绍了如何使用Go语言处理HTTP动态请求,设置根URL和静态文件服务,以及如何组织和访问静态资源。通过实例说明了如何避免URL解析混乱,确保清晰的URL结构。
137

被折叠的 条评论
为什么被折叠?



