daemon.go 1.41 KB
Newer Older
1
package commands
2 3

import (
4
	"fmt"
5 6
	"net/http"

7 8
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
	manet "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/net"
9

10 11
	cmds "github.com/jbenet/go-ipfs/commands"
	cmdsHttp "github.com/jbenet/go-ipfs/commands/http"
12
	"github.com/jbenet/go-ipfs/core"
13
	daemon "github.com/jbenet/go-ipfs/daemon2"
14 15
)

16
var daemonCmd = &cmds.Command{
17
	Private:     true,
18 19 20 21 22 23
	Options:     []cmds.Option{},
	Help:        "TODO",
	Subcommands: map[string]*cmds.Command{},
	Run:         daemonFunc,
}

24
func daemonFunc(res cmds.Response, req cmds.Request) {
25
	ctx := req.Context()
26

27
	lk, err := daemon.Lock(ctx.ConfigRoot)
28
	if err != nil {
29
		res.SetError(fmt.Errorf("Couldn't obtain lock. Is another daemon already running?"), cmds.ErrNormal)
30 31
		return
	}
32
	defer lk.Close()
33

34
	node, err := core.NewIpfsNode(ctx.Config, true)
35
	if err != nil {
36
		res.SetError(err, cmds.ErrNormal)
37 38
		return
	}
39
	ctx.Node = node
40

41
	addr, err := ma.NewMultiaddr(ctx.Config.Addresses.API)
42 43 44 45 46 47 48 49 50 51 52
	if err != nil {
		res.SetError(err, cmds.ErrNormal)
		return
	}

	_, host, err := manet.DialArgs(addr)
	if err != nil {
		res.SetError(err, cmds.ErrNormal)
		return
	}

53
	handler := cmdsHttp.Handler{*ctx, Root}
54
	http.Handle(cmdsHttp.ApiPath+"/", handler)
55 56 57

	fmt.Printf("API server listening on '%s'\n", host)

58
	err = http.ListenAndServe(host, nil)
59 60 61 62 63
	if err != nil {
		res.SetError(err, cmds.ErrNormal)
		return
	}
}