daemon.go 1.38 KB
Newer Older
1 2 3
package main

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 17 18 19 20 21 22 23
)

var Daemon = &cmds.Command{
	Options:     []cmds.Option{},
	Help:        "TODO",
	Subcommands: map[string]*cmds.Command{},
	Run:         daemonFunc,
}

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

26 27 28 29 30 31 32
	node, err := core.NewIpfsNode(ctx.Config, true)
	if err != nil {
		res.SetError(err, cmds.ErrNormal)
		return
	}
	ctx.Node = node

33
	lk, err := daemon.Lock(ctx.ConfigRoot)
34 35 36 37 38 39
	if err != nil {
		res.SetError(fmt.Errorf("Couldn't obtain lock. Is another daemon already running?"), cmds.ErrNormal)
		return
	}
	defer lk.Close()

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

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

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

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

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