github.com/keltia/go-ipfs@v0.3.8-0.20150909044612-210793031c63/core/corehttp/gateway.go (about) 1 package corehttp 2 3 import ( 4 "fmt" 5 "net" 6 "net/http" 7 "sync" 8 9 core "github.com/ipfs/go-ipfs/core" 10 id "github.com/ipfs/go-ipfs/p2p/protocol/identify" 11 ) 12 13 // Gateway should be instantiated using NewGateway 14 type Gateway struct { 15 Config GatewayConfig 16 } 17 18 type GatewayConfig struct { 19 Headers map[string][]string 20 BlockList *BlockList 21 Writable bool 22 } 23 24 func NewGateway(conf GatewayConfig) *Gateway { 25 return &Gateway{ 26 Config: conf, 27 } 28 } 29 30 func (g *Gateway) ServeOption() ServeOption { 31 return func(n *core.IpfsNode, _ net.Listener, mux *http.ServeMux) (*http.ServeMux, error) { 32 // pass user's HTTP headers 33 cfg, err := n.Repo.Config() 34 if err != nil { 35 return nil, err 36 } 37 38 g.Config.Headers = cfg.Gateway.HTTPHeaders 39 40 gateway, err := newGatewayHandler(n, g.Config) 41 if err != nil { 42 return nil, err 43 } 44 mux.Handle("/ipfs/", gateway) 45 mux.Handle("/ipns/", gateway) 46 return mux, nil 47 } 48 } 49 50 func GatewayOption(writable bool) ServeOption { 51 g := NewGateway(GatewayConfig{ 52 Writable: writable, 53 BlockList: &BlockList{}, 54 }) 55 return g.ServeOption() 56 } 57 58 func VersionOption() ServeOption { 59 return func(n *core.IpfsNode, _ net.Listener, mux *http.ServeMux) (*http.ServeMux, error) { 60 mux.HandleFunc("/version", func(w http.ResponseWriter, r *http.Request) { 61 fmt.Fprintf(w, "Client Version: %s\n", id.ClientVersion) 62 fmt.Fprintf(w, "Protocol Version: %s\n", id.IpfsVersion) 63 }) 64 return mux, nil 65 } 66 } 67 68 // Decider decides whether to Allow string 69 type Decider func(string) bool 70 71 type BlockList struct { 72 mu sync.RWMutex 73 Decider Decider 74 } 75 76 func (b *BlockList) ShouldAllow(s string) bool { 77 b.mu.RLock() 78 d := b.Decider 79 b.mu.RUnlock() 80 if d == nil { 81 return true 82 } 83 return d(s) 84 } 85 86 // SetDecider atomically swaps the blocklist's decider. This method is 87 // thread-safe. 88 func (b *BlockList) SetDecider(d Decider) { 89 b.mu.Lock() 90 b.Decider = d 91 b.mu.Unlock() 92 } 93 94 func (b *BlockList) ShouldBlock(s string) bool { 95 return !b.ShouldAllow(s) 96 }