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

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

verokarhu's avatar
verokarhu committed
7
	"github.com/gorilla/mux"
verokarhu's avatar
verokarhu committed
8
	mh "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multihash"
verokarhu's avatar
verokarhu committed
9 10 11
	core "github.com/jbenet/go-ipfs/core"
)

12 13 14 15
type handler struct {
	ipfs
}

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

	return http.ListenAndServe(address, nil)
}

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

30
	nd, err := i.ResolvePath(path)
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 41
func (i *handler) postHandler(w http.ResponseWriter, r *http.Request) {
	nd, err := i.NewDagFromReader(r.Body)
verokarhu's avatar
verokarhu committed
42 43
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
verokarhu's avatar
verokarhu committed
44
		fmt.Println(err)
verokarhu's avatar
verokarhu committed
45 46
		return
	}
verokarhu's avatar
verokarhu committed
47

verokarhu's avatar
verokarhu committed
48
	k, err := i.AddNodeToDAG(nd)
verokarhu's avatar
verokarhu committed
49 50
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
verokarhu's avatar
verokarhu committed
51
		fmt.Println(err)
verokarhu's avatar
verokarhu committed
52 53 54 55 56
		return
	}

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