github.com/zignig/go-ipfs@v0.0.0-20141111235910-c9e5fdf55a52/server/http/http.go (about) 1 // package http implements an http server that serves static content from ipfs 2 package http 3 4 import ( 5 "fmt" 6 "io" 7 "net/http" 8 9 "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/gorilla/mux" 10 ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr" 11 manet "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/net" 12 mh "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multihash" 13 14 core "github.com/jbenet/go-ipfs/core" 15 ) 16 17 type handler struct { 18 ipfs 19 } 20 21 // Serve starts the http server 22 func Serve(address ma.Multiaddr, node *core.IpfsNode) error { 23 r := mux.NewRouter() 24 handler := &handler{&ipfsHandler{node}} 25 26 r.HandleFunc("/ipfs/", handler.postHandler).Methods("POST") 27 r.PathPrefix("/ipfs/").Handler(handler).Methods("GET") 28 29 http.Handle("/", r) 30 31 _, host, err := manet.DialArgs(address) 32 if err != nil { 33 return err 34 } 35 36 return http.ListenAndServe(host, nil) 37 } 38 39 func (i *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { 40 path := r.URL.Path[5:] 41 42 nd, err := i.ResolvePath(path) 43 if err != nil { 44 w.WriteHeader(http.StatusInternalServerError) 45 fmt.Println(err) 46 return 47 } 48 49 dr, err := i.NewDagReader(nd) 50 if err != nil { 51 // TODO: return json object containing the tree data if it's a directory (err == ErrIsDir) 52 w.WriteHeader(http.StatusInternalServerError) 53 fmt.Println(err) 54 return 55 } 56 57 io.Copy(w, dr) 58 } 59 60 func (i *handler) postHandler(w http.ResponseWriter, r *http.Request) { 61 nd, err := i.NewDagFromReader(r.Body) 62 if err != nil { 63 w.WriteHeader(http.StatusInternalServerError) 64 fmt.Println(err) 65 return 66 } 67 68 k, err := i.AddNodeToDAG(nd) 69 if err != nil { 70 w.WriteHeader(http.StatusInternalServerError) 71 fmt.Println(err) 72 return 73 } 74 75 //TODO: return json representation of list instead 76 w.WriteHeader(http.StatusCreated) 77 w.Write([]byte(mh.Multihash(k).B58String())) 78 }