docserver.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package docserver
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. "path/filepath"
  7. "github.com/ethereum/go-ethereum/common"
  8. "github.com/ethereum/go-ethereum/crypto"
  9. )
  10. type DocServer struct {
  11. *http.Transport
  12. DocRoot string
  13. schemes []string
  14. }
  15. func New(docRoot string) (self *DocServer) {
  16. self = &DocServer{
  17. Transport: &http.Transport{},
  18. DocRoot: docRoot,
  19. schemes: []string{"file"},
  20. }
  21. self.RegisterProtocol("file", http.NewFileTransport(http.Dir(self.DocRoot)))
  22. return
  23. }
  24. // Clients should be reused instead of created as needed. Clients are safe for concurrent use by multiple goroutines.
  25. // A Client is higher-level than a RoundTripper (such as Transport) and additionally handles HTTP details such as cookies and redirects.
  26. func (self *DocServer) Client() *http.Client {
  27. return &http.Client{
  28. Transport: self,
  29. }
  30. }
  31. func (self *DocServer) RegisterScheme(scheme string, rt http.RoundTripper) {
  32. self.schemes = append(self.schemes, scheme)
  33. self.RegisterProtocol(scheme, rt)
  34. }
  35. func (self *DocServer) HasScheme(scheme string) bool {
  36. for _, s := range self.schemes {
  37. if s == scheme {
  38. return true
  39. }
  40. }
  41. return false
  42. }
  43. func (self *DocServer) GetAuthContent(uri string, hash common.Hash) (content []byte, err error) {
  44. // retrieve content
  45. url := uri
  46. fmt.Printf("uri: %v\n", url)
  47. content, err = self.Get(url, "")
  48. if err != nil {
  49. return
  50. }
  51. // check hash to authenticate content
  52. hashbytes := crypto.Sha3(content)
  53. var chash common.Hash
  54. copy(chash[:], hashbytes)
  55. if chash != hash {
  56. content = nil
  57. err = fmt.Errorf("content hash mismatch")
  58. }
  59. return
  60. }
  61. // Get(uri, path) downloads the document at uri, if path is non-empty it
  62. // is interpreted as a filepath to which the contents are saved
  63. func (self *DocServer) Get(uri, path string) (content []byte, err error) {
  64. // retrieve content
  65. resp, err := self.Client().Get(uri)
  66. defer func() {
  67. if resp != nil {
  68. resp.Body.Close()
  69. }
  70. }()
  71. if err != nil {
  72. return
  73. }
  74. content, err = ioutil.ReadAll(resp.Body)
  75. if err != nil {
  76. return
  77. }
  78. if path != "" {
  79. var abspath string
  80. abspath, err = filepath.Abs(path)
  81. ioutil.WriteFile(abspath, content, 0700)
  82. }
  83. return
  84. }