http.go 1.31 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 7
	"github.com/gorilla/mux"
	core "github.com/jbenet/go-ipfs/core"
verokarhu's avatar
verokarhu committed
8 9
	"github.com/jbenet/go-ipfs/importer"
	mh "github.com/jbenet/go-multihash"
verokarhu's avatar
verokarhu committed
10 11 12 13 14 15
)

type ipfsHandler struct {
	node *core.IpfsNode
}

verokarhu's avatar
verokarhu committed
16
// Serve starts the http server
verokarhu's avatar
verokarhu committed
17 18 19 20 21 22 23 24 25
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
26 27 28 29 30 31 32 33 34
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
	}

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

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

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

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