-
Notifications
You must be signed in to change notification settings - Fork 376
/
http_api.go
99 lines (82 loc) · 2.46 KB
/
http_api.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package ipfsutil
import (
"context"
"net/http"
"sync"
"time"
"github.com/ipfs/go-ipfs/commands"
"github.com/ipfs/go-ipfs/core"
"github.com/ipfs/go-ipfs/core/corehttp"
ma "github.com/multiformats/go-multiaddr"
manet "github.com/multiformats/go-multiaddr/net"
"go.uber.org/zap"
"berty.tech/berty/v2/go/pkg/errcode"
ipfswebui "berty.tech/ipfs-webui-packed"
)
// ServeHTTPApi collects options, creates listener, prints status message and starts serving requests
func ServeHTTPApi(logger *zap.Logger, node *core.IpfsNode, rootDirectory string) error {
// mandatory for the IPFS API server
cctx := commands.Context{
// needed for config access
ConfigRoot: rootDirectory,
// http handler requires it
ReqLog: &commands.ReqLog{},
// the node is already construct so we pass it
ConstructNode: func() (*core.IpfsNode, error) {
return node, nil
},
}
var APIAddr string
cfg, err := node.Repo.Config()
if err != nil || len(cfg.Addresses.API) == 0 {
APIAddr = "/ip4/127.0.0.1/tcp/5001"
} else {
APIAddr = cfg.Addresses.API[0]
}
opts := []corehttp.ServeOption{
corehttp.CommandsOption(cctx),
// allow redirections from the http://{apiAddr}/webui to the actual webui address
corehttp.WebUIOption,
corehttp.GatewayOption(false, corehttp.WebUIPaths...),
}
addr, err := ma.NewMultiaddr(APIAddr)
if err != nil {
return errcode.TODO.Wrap(err)
}
list, err := manet.Listen(addr)
if err != nil {
return errcode.TODO.Wrap(err)
}
addr = list.Multiaddr()
logger.Info("IPFS API server listening", zap.Stringer("addr", addr))
// start the server in a new goroutine since it is not async
go func(node *core.IpfsNode, opts ...corehttp.ServeOption) {
err := corehttp.Serve(node, manet.NetListener(list), opts...)
if err != nil {
logger.Error("corehttp.ListenAndServe failed", zap.Error(err))
}
}(node, opts...)
return nil
}
func ServeHTTPWebui(listenerAddr string, logger *zap.Logger) func() {
if listenerAddr == "" {
return nil
}
dir := http.FileServer(ipfswebui.Dir())
server := &http.Server{Addr: listenerAddr, Handler: dir}
wg := &sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
logger.Named("ipfs.webui").Error(server.ListenAndServe().Error())
}()
cleanup := func() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*4)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
logger.Named("ipfs.webui").Error("failed to shutdown webui server", zap.Error(err))
}
wg.Wait()
}
return cleanup
}