2017-01-26 7 views
0

HTTPサーバーからファイルをダウンロードするときに、何らかの種類のファイルチェックサム(SHA-256ハッシュなど)を知りたいと思います。 HTTP応答ヘッダーの1つとして転送できます。これにチェックサムヘッダーを正しく追加するにはどうすればよいですか?

私は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)) 
} 

答えて

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 
} 

を、チェックサムをボディ、ヘッダーを設定

+0

私はgolang.orgのWebサイトを見ていましたが、ResponseRecorder型がrwWrapperよりも優れた実装と思われますか? – Daniel

+0

[ResponseRecorder](https://godoc.org/net/http/httptest#ResponseRecorder)を使用する利点はありません。それを使用する場合は、rwWrapperタイプを削除し、レコーダー内のヘッダーを応答ライターにコピーするコードを追加します。 –

関連する問題