《Web Development with Go》Middleware之使用gorilla.handlers
2024-10-11 16:06:32
可以方便的使用日志和压缩等功能。
package main import ( "fmt" "log" "net/http" "os" "github.com/gorilla/handlers" ) func index(w http.ResponseWriter, r *http.Request) { log.Println("Executing index handler") fmt.Fprintf(w, "welcome!") } func about(w http.ResponseWriter, r *http.Request) { log.Println("Executing about handler") fmt.Fprintf(w, "Go Middleware!") } func iconHandler(w http.ResponseWriter, r *http.Request) { } func main() { http.HandleFunc("/favicon.ico", iconHandler) indexHandler := http.HandlerFunc(index) aboutHandler := http.HandlerFunc(about) logFile, err := os.OpenFile("server.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) if err != nil { panic(err) } http.Handle("/", handlers.LoggingHandler(logFile, handlers.CompressHandler(indexHandler))) http.Handle("/about", handlers.LoggingHandler(logFile, handlers.CompressHandler(aboutHandler))) server := &http.Server{ Addr: ":8080", } log.Println("Listening...") server.ListenAndServe() }
127.0.0.1 - - [01/Dec/2019:13:31:40 +0800] "GET / HTTP/1.1" 200 32 127.0.0.1 - - [01/Dec/2019:13:32:10 +0800] "GET /about HTTP/1.1" 200 38
最新文章
- LUA 学习笔记
- Android 双卡双待识别
- HBase自动分区
- UI坐标变换/转换
- spark reduce类操作
- C语言strlen函数和sizeof操作符
- git常见操作--忽略文件以及常用命令【转】
- JSP-tag文件使用介绍
- VS2010 Web项目需要缺少的Web组件才能加载
- JS遍历对象或者数组
- VS2010使用附加进程的方式调试IIS中的页面介绍
- Java中finally你知多少
- VS代码生成工具ReSharper发布8.1版本
- [转] iOS ABI Function Call Guide
- Linux显示历史记录
- 安装mysql8.0出现服务无法启动,服务没报告任何错误
- mysql [索引优化] -- in or替换为union all
- websocket连接的后台反向代理问题
- #CSS margin-top父元素下落
- 【Unity/Kinect】Kinect一些常用的API