magneticow api is now *completely* done!

This commit is contained in:
Bora Alper 2018-07-08 12:08:24 +03:00
parent ba1be368cf
commit a9cf795562
3 changed files with 53 additions and 5 deletions

View File

@ -1,6 +1,7 @@
package main
import (
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
@ -8,6 +9,7 @@ import (
"time"
"github.com/boramalper/magnetico/pkg/persistence"
"github.com/gorilla/mux"
"go.uber.org/zap"
)
@ -87,11 +89,57 @@ func apiTorrentsHandler(w http.ResponseWriter, r *http.Request) {
}
func apiTorrentsInfohashHandler(w http.ResponseWriter, r *http.Request) {
infohashHex := mux.Vars(r)["infohash"]
infohash, err := hex.DecodeString(infohashHex)
if err != nil {
respondError(w, 400, "couldn't decode infohash: %s", err.Error())
return
}
torrent, err := database.GetTorrent(infohash)
if err != nil {
respondError(w, 500, "couldn't get torrent: %s", err.Error())
return
}
// TODO: use plain Marshal
jm, err := json.MarshalIndent(torrent, "", " ")
if err != nil {
respondError(w, 500, "json marshalling error: %s", err.Error())
return
}
if _, err = w.Write(jm); err != nil {
zap.L().Warn("couldn't write http.ResponseWriter", zap.Error(err))
}
}
func apiFilesInfohashHandler(w http.ResponseWriter, r *http.Request) {
infohashHex := mux.Vars(r)["infohash"]
infohash, err := hex.DecodeString(infohashHex)
if err != nil {
respondError(w, 400, "couldn't decode infohash: %s", err.Error())
return
}
files, err := database.GetFiles(infohash)
if err != nil {
respondError(w, 500, "couldn't get files: %s", err.Error())
return
}
// TODO: use plain Marshal
jm, err := json.MarshalIndent(files, "", " ")
if err != nil {
respondError(w, 500, "json marshalling error: %s", err.Error())
return
}
if _, err = w.Write(jm); err != nil {
zap.L().Warn("couldn't write http.ResponseWriter", zap.Error(err))
}
}
func apiStatisticsHandler(w http.ResponseWriter, r *http.Request) {

View File

@ -57,12 +57,12 @@ func main() {
router.HandleFunc("/", rootHandler)
router.HandleFunc("/api/v0.1/torrents", apiTorrentsHandler)
router.HandleFunc("/api/v0.1/torrents/{infohash:[a-z0-9]{40}}", apiTorrentsInfohashHandler)
router.HandleFunc("/api/v0.1/files/{infohash:[a-z0-9]{40}}", apiFilesInfohashHandler)
router.HandleFunc("/api/v0.1/torrents/{infohash:[a-f0-9]{40}}", apiTorrentsInfohashHandler)
router.HandleFunc("/api/v0.1/files/{infohash:[a-f0-9]{40}}", apiFilesInfohashHandler)
router.HandleFunc("/api/v0.1/statistics", apiStatisticsHandler)
router.HandleFunc("/torrents", torrentsHandler)
router.HandleFunc("/torrents/{infohash:[a-z0-9]{40}}", torrentsInfohashHandler)
router.HandleFunc("/torrents/{infohash:[a-f0-9]{40}}", torrentsInfohashHandler)
router.HandleFunc("/statistics", statisticsHandler)
router.HandleFunc("/feed", feedHandler)

View File

@ -69,8 +69,8 @@ type Statistics struct {
}
type File struct {
Size int64
Path string
Size int64 `json:"size"`
Path string `json:"path"`
}
type TorrentMetadata struct {