http.go 1.32 KB
Newer Older
verokarhu's avatar
verokarhu committed
1 2 3 4 5
package http

import (
	"github.com/gorilla/mux"
	core "github.com/jbenet/go-ipfs/core"
verokarhu's avatar
verokarhu committed
6 7
	"github.com/jbenet/go-ipfs/importer"
	mh "github.com/jbenet/go-multihash"
verokarhu's avatar
verokarhu committed
8 9 10 11 12 13 14
	"net/http"
)

type ipfsHandler struct {
	node *core.IpfsNode
}

verokarhu's avatar
verokarhu committed
15
// Serve starts the http server
verokarhu's avatar
verokarhu committed
16 17 18 19 20 21 22 23 24
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
25 26 27 28 29 30 31 32 33
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
34
	// TODO: return json object containing the tree data if it's a folder
verokarhu's avatar
verokarhu committed
35
	w.Write(nd.Data)
verokarhu's avatar
verokarhu committed
36 37
}

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

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

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