docserver.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package docserver
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. "github.com/ethereum/go-ethereum/common"
  7. "github.com/ethereum/go-ethereum/crypto"
  8. )
  9. // http://golang.org/pkg/net/http/#RoundTripper
  10. var (
  11. schemes = map[string]func(*DocServer) http.RoundTripper{
  12. // Simple File server from local disk file:///etc/passwd :)
  13. "file": fileServerOnDocRoot,
  14. // Swarm RoundTripper for bzz scheme bzz://mydomain/contact/twitter.json
  15. // "bzz": &bzz.FileServer{},
  16. // swarm remote file system call bzzfs:///etc/passwd
  17. // "bzzfs": &bzzfs.FileServer{},
  18. // restful peer protocol RoundTripper for enode scheme:
  19. // POST suggestPeer DELETE removePeer PUT switch protocols
  20. // RPC - standard protocol provides arc API for self enode (very safe remote server only connects to registered enode)
  21. // POST enode://ae234dfgc56b..@128.56.68.5:3456/eth/getBlock/356eac67890fe
  22. // and remote peer protocol
  23. // POST enode://ae234dfgc56b..@128.56.68.5:3456/eth/getBlock/356eac67890fe
  24. // proxy protoocol
  25. }
  26. )
  27. func fileServerOnDocRoot(ds *DocServer) http.RoundTripper {
  28. return http.NewFileTransport(http.Dir(ds.DocRoot))
  29. }
  30. type DocServer struct {
  31. *http.Transport
  32. DocRoot string
  33. }
  34. func New(docRoot string) (self *DocServer, err error) {
  35. self = &DocServer{
  36. Transport: &http.Transport{},
  37. DocRoot: docRoot,
  38. }
  39. err = self.RegisterProtocols(schemes)
  40. return
  41. }
  42. // Clients should be reused instead of created as needed. Clients are safe for concurrent use by multiple goroutines.
  43. // A Client is higher-level than a RoundTripper (such as Transport) and additionally handles HTTP details such as cookies and redirects.
  44. func (self *DocServer) Client() *http.Client {
  45. return &http.Client{
  46. Transport: self,
  47. }
  48. }
  49. func (self *DocServer) RegisterProtocols(schemes map[string]func(*DocServer) http.RoundTripper) (err error) {
  50. for scheme, rtf := range schemes {
  51. self.RegisterProtocol(scheme, rtf(self))
  52. }
  53. return
  54. }
  55. func (self *DocServer) GetAuthContent(uri string, hash common.Hash) (content []byte, err error) {
  56. // retrieve content
  57. resp, err := self.Client().Get(uri)
  58. defer resp.Body.Close()
  59. if err != nil {
  60. return
  61. }
  62. content, err = ioutil.ReadAll(resp.Body)
  63. if err != nil {
  64. return
  65. }
  66. // check hash to authenticate content
  67. hashbytes := crypto.Sha3(content)
  68. var chash common.Hash
  69. copy(chash[:], hashbytes)
  70. if chash != hash {
  71. content = nil
  72. err = fmt.Errorf("content hash mismatch")
  73. }
  74. return
  75. }