beginnings of an http gateway/api
verokarhu committed
Aug 6, 2014 at 00:14 UTC
0427d1efa114eb70f951d9bbebdc32cccc750d00
3 files changed
+62
cmd/ipfs/ipfs.go
+2
@@ -35,6 +35,7 @@ Tool commands:
35
Advanced Commands:
36
37
mount Mount an ipfs read-only mountpoint.
38
+ serve Serve an http gateway into ipfs.
39
40
Use "ipfs help <command>" for more information about a command.
41
`,
@@ -49,6 +50,7 @@ Use "ipfs help <command>" for more information about a command.
50
cmdIpfsCommands,
51
cmdIpfsMount,
52
cmdIpfsInit,
53
+ cmdIpfsServe,
54
},
55
Flag: *flag.NewFlagSet("ipfs", flag.ExitOnError),
56
}
cmd/ipfs/serve.go
new
+24
@@ -0,0 +1,24 @@
1
+package main
2
+
3
+import (
4
+ "github.com/gonuts/flag"
5
+ "github.com/jbenet/commander"
6
+ h "github.com/jbenet/go-ipfs/http"
7
+)
8
+
9
+var cmdIpfsServe = &commander.Command{
10
+ UsageLine: "serve",
11
+ Short: "Serve an HTTP API",
12
+ Long: `ipfs serve - Serve an http gateway into ipfs.`,
13
+ Run: serveCmd,
14
+ Flag: *flag.NewFlagSet("ipfs-serve", flag.ExitOnError),
15
+}
16
+
17
+func serveCmd(c *commander.Command, _ []string) error {
18
+ n, err := localNode()
19
+ if err != nil {
20
+ return err
21
+ }
22
+
23
+ return h.Serve("127.0.0.1", 80, n)
24
+}
http/http.go
new
+36
@@ -0,0 +1,36 @@
1
+package http
2
+
3
+import (
4
+ "fmt"
5
+ "github.com/gorilla/mux"
6
+ core "github.com/jbenet/go-ipfs/core"
7
+ "net/http"
8
+ "strconv"
9
+)
10
+
11
+type ipfsHandler struct {
12
+ node *core.IpfsNode
13
+}
14
+
15
+func (i *ipfsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
16
+ path := r.URL.Path
17
+
18
+ nd, err := i.node.Resolver.ResolvePath(path)
19
+ if err != nil {
20
+ w.WriteHeader(http.StatusInternalServerError)
21
+ return
22
+ }
23
+
24
+ fmt.Fprintf(w, "%s", nd.Data)
25
+}
26
+
27
+func Serve(host string, port uint16, node *core.IpfsNode) error {
28
+ r := mux.NewRouter()
29
+ r.PathPrefix("/").Handler(&ipfsHandler{node}).Methods("GET")
30
+ http.Handle("/", r)
31
+
32
+ address := host + ":" + strconv.FormatUint(uint64(port), 10)
33
+ fmt.Printf("Serving on %s\n", address)
34
+
35
+ return http.ListenAndServe(address, nil)
36
+}