kubo/core/corehttp/gateway.go
Kevin Wallace fbd76ebb5b corehttp: ServeOption supports chaining muxes
Each option now additionally returns the mux to be used by future options. If
every options returns the mux it was passed, the current behavior is unchanged.

However, if the option returns an a new mux, it can mediate requests to handlers
provided by future options:

    return func(n *core.IpfsNode, mux *http.ServeMux) (*http.ServeMux, error) {
      childMux := http.NewServeMux()
      mux.Handle("/", handlerThatDelegatesToChildMux)
      return childMux, nil
    }

License: MIT
Signed-off-by: Kevin Wallace <kevin@pentabarf.net>
2015-02-08 11:27:06 -08:00

75 lines
1.3 KiB
Go

package corehttp
import (
"net/http"
"sync"
core "github.com/jbenet/go-ipfs/core"
)
// Gateway should be instantiated using NewGateway
type Gateway struct {
Config GatewayConfig
}
type GatewayConfig struct {
BlockList *BlockList
Writable bool
}
func NewGateway(conf GatewayConfig) *Gateway {
return &Gateway{
Config: conf,
}
}
func (g *Gateway) ServeOption() ServeOption {
return func(n *core.IpfsNode, mux *http.ServeMux) (*http.ServeMux, error) {
gateway, err := newGatewayHandler(n, g.Config)
if err != nil {
return nil, err
}
mux.Handle("/ipfs/", gateway)
mux.Handle("/ipns/", gateway)
return mux, nil
}
}
func GatewayOption(writable bool) ServeOption {
g := NewGateway(GatewayConfig{
Writable: writable,
BlockList: &BlockList{},
})
return g.ServeOption()
}
// Decider decides whether to Allow string
type Decider func(string) bool
type BlockList struct {
mu sync.RWMutex
Decider Decider
}
func (b *BlockList) ShouldAllow(s string) bool {
b.mu.RLock()
d := b.Decider
b.mu.RUnlock()
if d == nil {
return true
}
return d(s)
}
// SetDecider atomically swaps the blocklist's decider. This method is
// thread-safe.
func (b *BlockList) SetDecider(d Decider) {
b.mu.Lock()
b.Decider = d
b.mu.Unlock()
}
func (b *BlockList) ShouldBlock(s string) bool {
return !b.ShouldAllow(s)
}