http处理器示例
处理器调用的http.Handle函数来处理web容器
用处理器编写文件服务器
package main
import (
"net/http"
)
func main(){
addr:=":8888"
//http.Dir 类型转换,而不是函数
http.Handle("/static",http.FileServer(http.Dir("./static"))) //会在当前的static路径下寻找static路径,即访问的资源是 /static/static/xxx.x
http.Handle("/static",http.FileServer(http.Dir("."))) //访问的文件路径为 ./static
http.Handle("/www",http.StripPrefix(http.FileServer(http.Dir("./static/")))) //访问的文件路径为 ./static;StripPrefix函数会截取调前面的www,即访问的路径不会是 /www/static
http.ListenAndServe(addr,nil)
}
面向对象的处理器
Handle函数的第二个参数是一个handler,而handler是一个结构,需要满足一个 ServeHTTP的方法
type Help struct{}
func (h *Help) ServeHTTP(w http.ResponseWriter,r http.Request){ //指针类型的结构体方法
fmt.Fprint(w,"help")
}
func main(){
http.Handle("/help",new(Help))
http.ListenAndServe(addr,nil)
}
文档更新时间: 2021-08-22 17:29 作者:张尚