http处理器示例

处理器调用的http.Handle函数来处理web容器

用处理器编写文件服务器
  1. package main
  2. import (
  3. "net/http"
  4. )
  5. func main(){
  6. addr:=":8888"
  7. //http.Dir 类型转换,而不是函数
  8. http.Handle("/static",http.FileServer(http.Dir("./static"))) //会在当前的static路径下寻找static路径,即访问的资源是 /static/static/xxx.x
  9. http.Handle("/static",http.FileServer(http.Dir("."))) //访问的文件路径为 ./static
  10. http.Handle("/www",http.StripPrefix(http.FileServer(http.Dir("./static/")))) //访问的文件路径为 ./static;StripPrefix函数会截取调前面的www,即访问的路径不会是 /www/static
  11. http.ListenAndServe(addr,nil)
  12. }
面向对象的处理器

Handle函数的第二个参数是一个handler,而handler是一个结构,需要满足一个 ServeHTTP的方法

  1. type Help struct{}
  2. func (h *Help) ServeHTTP(w http.ResponseWriter,r http.Request){ //指针类型的结构体方法
  3. fmt.Fprint(w,"help")
  4. }
  5. func main(){
  6. http.Handle("/help",new(Help))
  7. http.ListenAndServe(addr,nil)
  8. }
文档更新时间: 2021-08-22 17:29   作者:张尚