http.go 1.52 KB
Newer Older
verokarhu's avatar
verokarhu committed
1 2 3
package http

import (
verokarhu's avatar
verokarhu committed
4 5
	"net/http"

verokarhu's avatar
verokarhu committed
6
	"github.com/gorilla/mux"
verokarhu's avatar
verokarhu committed
7
	mh "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multihash"
verokarhu's avatar
verokarhu committed
8
	core "github.com/jbenet/go-ipfs/core"
verokarhu's avatar
verokarhu committed
9
	"github.com/jbenet/go-ipfs/importer"
verokarhu's avatar
verokarhu committed
10
	merkledag "github.com/jbenet/go-ipfs/merkledag"
verokarhu's avatar
verokarhu committed
11 12 13 14 15 16
)

type ipfsHandler struct {
	node *core.IpfsNode
}

verokarhu's avatar
verokarhu committed
17
// Serve starts the http server
verokarhu's avatar
verokarhu committed
18 19 20 21 22 23 24 25 26
func Serve(address string, node *core.IpfsNode) error {
	r := mux.NewRouter()
	r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { ipfsPostHandler(w, r, node) }).Methods("POST")
	r.PathPrefix("/").Handler(&ipfsHandler{node}).Methods("GET")
	http.Handle("/", r)

	return http.ListenAndServe(address, nil)
}

verokarhu's avatar
verokarhu committed
27 28 29
func (i *ipfsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Path

verokarhu's avatar
verokarhu committed
30
	nd, err := resolvePath(path, i.node)
verokarhu's avatar
verokarhu committed
31 32 33 34 35
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

verokarhu's avatar
verokarhu committed
36
	// TODO: return json object containing the tree data if it's a folder
verokarhu's avatar
verokarhu committed
37
	w.Write(nd.Data)
verokarhu's avatar
verokarhu committed
38 39
}

verokarhu's avatar
verokarhu committed
40
func ipfsPostHandler(w http.ResponseWriter, r *http.Request, node *core.IpfsNode) {
verokarhu's avatar
verokarhu committed
41
	root, err := importer.NewDagFromReader(r.Body)
verokarhu's avatar
verokarhu committed
42 43 44 45
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
verokarhu's avatar
verokarhu committed
46

verokarhu's avatar
verokarhu committed
47
	k, err := node.DAG.Add(root)
verokarhu's avatar
verokarhu committed
48 49 50 51 52 53 54
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	//TODO: return json representation of list instead
	w.WriteHeader(http.StatusCreated)
verokarhu's avatar
verokarhu committed
55
	w.Write([]byte(mh.Multihash(k).B58String()))
verokarhu's avatar
verokarhu committed
56
}
verokarhu's avatar
verokarhu committed
57 58 59 60

var resolvePath = func(path string, node *core.IpfsNode) (*merkledag.Node, error) {
	return node.Resolver.ResolvePath(path)
}