explorer.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2019 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // go-ethereum is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "context"
  19. "fmt"
  20. "net"
  21. "net/http"
  22. "time"
  23. "github.com/ethereum/go-ethereum/log"
  24. "github.com/ethereum/go-ethereum/swarm/storage/mock"
  25. "github.com/ethereum/go-ethereum/swarm/storage/mock/explorer"
  26. cli "gopkg.in/urfave/cli.v1"
  27. )
  28. // serveChunkExplorer starts an http server in background with chunk explorer handler
  29. // using the provided global store. Server is started if the returned shutdown function
  30. // is not nil.
  31. func serveChunkExplorer(ctx *cli.Context, globalStore mock.GlobalStorer) (shutdown func(), err error) {
  32. if !ctx.IsSet("explorer-address") {
  33. return nil, nil
  34. }
  35. corsOrigins := ctx.StringSlice("explorer-cors-origin")
  36. server := &http.Server{
  37. Handler: explorer.NewHandler(globalStore, corsOrigins),
  38. IdleTimeout: 30 * time.Minute,
  39. ReadTimeout: 2 * time.Minute,
  40. WriteTimeout: 2 * time.Minute,
  41. }
  42. listener, err := net.Listen("tcp", ctx.String("explorer-address"))
  43. if err != nil {
  44. return nil, fmt.Errorf("explorer: %v", err)
  45. }
  46. log.Info("chunk explorer http", "address", listener.Addr().String(), "origins", corsOrigins)
  47. go func() {
  48. if err := server.Serve(listener); err != nil {
  49. log.Error("chunk explorer", "err", err)
  50. }
  51. }()
  52. return func() {
  53. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  54. defer cancel()
  55. if err := server.Shutdown(ctx); err != nil {
  56. log.Error("chunk explorer: shutdown", "err", err)
  57. }
  58. }, nil
  59. }