diff --git a/cmd/ipfs/ipfs.go b/cmd/ipfs/ipfs.go index 8365e532a318a08b3ec5a3a35e4324245a91497b..d4904bd2c5e1ce245ef84fc04dbed279d2276766 100644 --- a/cmd/ipfs/ipfs.go +++ b/cmd/ipfs/ipfs.go @@ -35,6 +35,7 @@ Tool commands: Advanced Commands: mount Mount an ipfs read-only mountpoint. + serve Serve an http gateway into ipfs. Use "ipfs help <command>" for more information about a command. `, @@ -49,6 +50,7 @@ Use "ipfs help <command>" for more information about a command. cmdIpfsCommands, cmdIpfsMount, cmdIpfsInit, + cmdIpfsServe, }, Flag: *flag.NewFlagSet("ipfs", flag.ExitOnError), } diff --git a/cmd/ipfs/serve.go b/cmd/ipfs/serve.go new file mode 100644 index 0000000000000000000000000000000000000000..367ec6e71cd157e5d5d3de8ff0a2fd58fe648dc0 --- /dev/null +++ b/cmd/ipfs/serve.go @@ -0,0 +1,24 @@ +package main + +import ( + "github.com/gonuts/flag" + "github.com/jbenet/commander" + h "github.com/jbenet/go-ipfs/http" +) + +var cmdIpfsServe = &commander.Command{ + UsageLine: "serve", + Short: "Serve an HTTP API", + Long: `ipfs serve - Serve an http gateway into ipfs.`, + Run: serveCmd, + Flag: *flag.NewFlagSet("ipfs-serve", flag.ExitOnError), +} + +func serveCmd(c *commander.Command, _ []string) error { + n, err := localNode() + if err != nil { + return err + } + + return h.Serve("127.0.0.1", 80, n) +} diff --git a/http/http.go b/http/http.go new file mode 100644 index 0000000000000000000000000000000000000000..9d10c4673d64e2d4dbdbab39adc961c82d4ed090 --- /dev/null +++ b/http/http.go @@ -0,0 +1,36 @@ +package http + +import ( + "fmt" + "github.com/gorilla/mux" + core "github.com/jbenet/go-ipfs/core" + "net/http" + "strconv" +) + +type ipfsHandler struct { + node *core.IpfsNode +} + +func (i *ipfsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + path := r.URL.Path + + nd, err := i.node.Resolver.ResolvePath(path) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + return + } + + fmt.Fprintf(w, "%s", nd.Data) +} + +func Serve(host string, port uint16, node *core.IpfsNode) error { + r := mux.NewRouter() + r.PathPrefix("/").Handler(&ipfsHandler{node}).Methods("GET") + http.Handle("/", r) + + address := host + ":" + strconv.FormatUint(uint64(port), 10) + fmt.Printf("Serving on %s\n", address) + + return http.ListenAndServe(address, nil) +}