go 语言内置的 handlers

http.NotFoundHandler

func NotFoundHandler() Handler

返回一个 handler, 响应一个 404;

package main

import "net/http"

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Home"))
	})
	http.Handle("/test", http.NotFoundHandler())
	http.ListenAndServe(":80", nil)
}

http.Redirect

func Redirect(w ResponseWriter, r *Request, url string, code int)

http.Redirect 可以进行重定向 :

package main

import "net/http"

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Home"))
	})
	http.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
		http.Redirect(w, r, "/", http.StatusFound)
	})
	http.ListenAndServe(":80", nil)
}

http.StripPrefix()

func StripPrefix(prefix string, h Handler) Handler

StripPrefix将URL中的前缀中的prefix字符串删除,然后再交给后面的Handler处理,一般是http.FileServer()的返回值。

如果URL不是以prefix开始,或者prefix包含转移字符,最后结果都会返回404,因此要精确匹配URL和prefix;

http.StripPrefix 更像一个中间件 ~

http.TimeoutHandler

func TimeoutHandler(h Handler dt time.Duration, msg string Handler

返回一个 handler,它用来在指定时间内运行传入的 handler。也相当于是一个修饰器

h,将要被修饰的 handler
dt,第一个 handler 允许的处理时间
msg,如果超时,那么就把 msg 返回给请求,表示响应时间过长

示例

package main

import (
	"net/http"
	"time"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Home"))
	})
	http.Handle("/slow", http.TimeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		time.Sleep(time.Second * 3)
		w.Write([]byte("slow"))
	}), time.Second*2, "Timeout..."))
	http.ListenAndServe(":80", nil)
}

http.FileServer

func FileServer(root FileSystem) Handler

http.FileServer 方法属于标准库 nettp,返回一个使用 FileSystem 接口 root 提供文件访问服务的 HTTP 处理器。可以方便的实现静态文件服务器。

使用时需要用到操作系统的文件系统,所以还需要委托给 :

type Dir string func (d Dir) Open(name string) (File, error)

示例一 基于不同 handler

package main

import (
	"net/http"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		println(r.URL.Path)
		http.ServeFile(w, r, "html"+r.URL.Path)
	})
	http.ListenAndServe(":80", nil)
}

示例二 整个站点为静态站点

package main

import (
	"net/http"
)

func main() {
	http.ListenAndServe(":80", http.FileServer(http.Dir("html")))
}