douci1541 2017-01-26 19:55
浏览 74
已采纳

如何正确地为此添加校验和标头?

I'd like to know some kind of file checksum (like SHA-256 hash, or anything else) when I start downloading a file from HTTP server. It could be transferred as one of HTTP response headers.

I know http etag is something similar, I think, but this is Golang which I am new to learning and although I have looked through some documentation, I am still clueless. Any help would be appreciated. This is what I have so far:

package main

import (
    "flag"
    "fmt"
    "log"
    "net/http"
    "strconv"
)

const (
    crlf       = "
"
    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.
"
        w.Header().Set("Content-Length", strconv.Itoa(len(msg)))
        fmt.Fprintf(w, msg)
    })))

    log.Fatal(http.ListenAndServe(*listenAddr, nil))
}
  • 写回答

1条回答 默认 最新

  • duaiwu8385 2017-01-26 20:20
    关注

    Write a wrapper around an http.ResponseWriter to capture the response body and status:

    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
    }
    

    After the handler returns, checksum the body, set the header and then write the body to the underlying response writer:

    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())
      })
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 定制ai直播实时换脸软件
  • ¥100 栈回溯相关,模块加载后KiExceptionDispatch无法正常回溯了
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件