当我开始从HTTP服务器下载文件时,我想知道某种文件校验和(如SHA-256哈希或其他任何东西)。它可以作为HTTP响应标头之一传输。
我知道http etag是类似的东西,我想,但这是Golang,我是新手学习的,虽然我查看过一些文档,但我仍然无能为力。任何帮助,将不胜感激。这就是我到目前为止所做的:
package main
import (
"flag"
"fmt"
"log"
"net/http"
"strconv"
)
const (
crlf = "\r\n"
colonspace = ": "
)
func Checksum(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
})
}
// Do not change this function.
func main() {
var listenAddr = flag.String("http", ":8080", "address to listen on for HTTP")
flag.Parse()
http.Handle("/", Checksum(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Foo", "bar")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Date", "Sun, 08 May 2016 14:04:53 GMT")
msg := "Curiosity is insubordination in its purest form.\n"
w.Header().Set("Content-Length", strconv.Itoa(len(msg)))
fmt.Fprintf(w, msg)
})))
log.Fatal(http.ListenAndServe(*listenAddr, nil))
}
答案 0 :(得分:2)
围绕http.ResponseWriter编写一个包装器以捕获响应主体和状态:
type rwWrapper struct {
http.ResponseWriter
buf bytes.Buffer
status int
}
func (w *rwWrapper) Write(p []byte) (int, error) {
return rw.buf.Write(p)
}
func (w *rwWrapper) WriteHeader(status int) {
rw.status = status
}
处理程序返回后,校验主体,设置标题,然后将主体写入底层响应编写器:
func Checksum(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ww := &rwWrapper{ResponseWriter: w, status:200}
h.ServeHttp(ww, r)
// compute checksum of ww.buf.Bytes() here
w.Header().Set("nameOfHeader", checksum)
w.WriteHeader(ww.status)
w.Write(ww.buf.Bytes())
})
}