Skip to content

Instantly share code, notes, and snippets.

@whyrusleeping
Created February 10, 2016 17:15
  • Select an option

Select an option

Revisions

  1. whyrusleeping created this gist Feb 10, 2016.
    75 changes: 75 additions & 0 deletions host-cmds.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,75 @@
    package main

    import (
    "fmt"
    "net"

    cmds "github.com/ipfs/go-ipfs/commands"
    core "github.com/ipfs/go-ipfs/core"
    corehttp "github.com/ipfs/go-ipfs/core/corehttp"
    corenet "github.com/ipfs/go-ipfs/core/corenet"
    fsrepo "github.com/ipfs/go-ipfs/repo/fsrepo"

    "golang.org/x/net/context"
    )

    func main() {

    // Basic ipfsnode setup
    r, err := fsrepo.Open("~/.ipfs")
    if err != nil {
    panic(err)
    }

    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()

    cfg := &core.BuildCfg{
    Repo: r,
    Online: true,
    }

    nd, err := core.NewNode(ctx, cfg)
    if err != nil {
    panic(err)
    }

    // create a tcp listener for the api, lets use port 5050
    netlist, err := net.Listen("tcp", "127.0.0.1:5050")
    if err != nil {
    panic(err)
    }

    // set up a context for the api server
    cctx := cmds.Context{
    ConstructNode: func() (*core.IpfsNode, error) {
    return nd, nil
    },
    }

    // do this in a separate goroutine since it will block
    go func() {
    err := corehttp.Serve(nd, netlist, corehttp.CommandsOption(cctx))
    if err != nil {
    fmt.Println("error serving api: ", err)
    }
    }()

    list, err := corenet.Listen(nd, "/app/whyrusleeping")
    if err != nil {
    panic(err)
    }
    fmt.Printf("I am peer: %s\n", nd.Identity.Pretty())

    for {
    con, err := list.Accept()
    if err != nil {
    fmt.Println(err)
    return
    }
    defer con.Close()

    fmt.Fprintln(con, "Hello! This is whyrusleepings awesome ipfs service")
    fmt.Printf("Connection from: %s\n", con.Conn().RemotePeer())
    }
    }