func TestDB(t *testing.T) {
	db, err := NewTorrentDB("test.db")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll("test.db")

	if n := NumTorrents(db); n != 0 {
		t.Fatalf("Expected 0 torrents, got %d", n)
	}

	r := core.Torrent{}
	r.Hash = "foo"
	if err := db.Add(&r); err != nil {
		t.Fatal(err)
	}

	n, err := db.Get("foo")
	if err != nil {
		t.Fatal(err)
	}

	if n.Hash != r.Hash {
		t.Fatalf("%v != %v", n, r)
	}
}
Example #2
0
func (th AddTorrentHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	decoder := json.NewDecoder(r.Body)
	var t core.Torrent
	err := decoder.Decode(&t)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	t.CreatedAt = time.Now()
	t.CalculateHash()

	th.db.Add(&t)

	js, err := json.Marshal(t)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.Write(js)
}