http.go 1.5 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
	"io"
verokarhu's avatar
verokarhu committed
6 7
	"net/http"

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

13 14 15 16
type handler struct {
	ipfs
}

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

	return http.ListenAndServe(address, nil)
}

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

31
	nd, err := i.ResolvePath(path)
verokarhu's avatar
verokarhu committed
32 33
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
verokarhu's avatar
verokarhu committed
34 35 36 37 38 39 40 41 42
		fmt.Println(err)
		return
	}

	dr, err := i.NewDagReader(nd)
	if err != nil {
		// TODO: return json object containing the tree data if it's a directory (err == ErrIsDir)
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Println(err)
verokarhu's avatar
verokarhu committed
43 44 45
		return
	}

verokarhu's avatar
verokarhu committed
46
	io.Copy(w, dr)
verokarhu's avatar
verokarhu committed
47 48
}

verokarhu's avatar
verokarhu committed
49 50
func (i *handler) postHandler(w http.ResponseWriter, r *http.Request) {
	nd, err := i.NewDagFromReader(r.Body)
verokarhu's avatar
verokarhu committed
51 52
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
verokarhu's avatar
verokarhu committed
53
		fmt.Println(err)
verokarhu's avatar
verokarhu committed
54 55
		return
	}
verokarhu's avatar
verokarhu committed
56

verokarhu's avatar
verokarhu committed
57
	k, err := i.AddNodeToDAG(nd)
verokarhu's avatar
verokarhu committed
58 59
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
verokarhu's avatar
verokarhu committed
60
		fmt.Println(err)
verokarhu's avatar
verokarhu committed
61 62 63 64 65
		return
	}

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