Build your own Ipfs node and Http API

This snippet shows how to construct an ipfs 'core node' in go, and spin up the http api server to operate on that node. In effect, creating your own 'ipfs daemon'. This is useful for testing various things, or building your own application in go that wants to embed an ipfs daemon.

package main 
  
import ( 
        "context"  
        "log"
        "net"
  
        commands "github.com/ipfs/go-ipfs/commands"  
        core "github.com/ipfs/go-ipfs/core"   
        corehttp "github.com/ipfs/go-ipfs/core/corehttp" 
) 
  
func main() {
        ctx, cancel := context.WithCancel(context.Background()) 
        defer cancel()  
  
        nd, err := core.NewNode(ctx, &core.BuildCfg{})   
        if err != nil { 
                log.Fatal(err) 
        }
  
        cctx := commands.Context{
                Online: true,
                ConstructNode: func() (*core.IpfsNode, error) {
                        return nd, nil
                },
        }

        list, err := net.Listen("tcp", ":0")
        if err != nil {
                log.Fatal(err)
        }

        log.Println("listening on: ", list.Addr())

        if err := corehttp.Serve(nd, list, corehttp.CommandsOption(cctx)); err != nil {
                log.Fatal(err)
        }
}