Albirew/nyaa-pantsu
Archivé
1
0
Bifurcation 0
Ce dépôt a été archivé le 2022-05-07. Vous pouvez voir ses fichiers ou le cloner, mais pas ouvrir de ticket ou de demandes d'ajout, ni soumettre de changements.
nyaa-pantsu/controllers/torrent/download.go
akuma06 2c8344faf9 Controllers are now separated
They are in different folders and all loaded in controllers/router.go.
This means that you only have to create a folder with a router.go file and import this folder in main router.go to add a handler.
2017-07-16 17:14:21 +02:00

54 lignes
1,5 Kio
Go

package torrentController
import (
"errors"
"fmt"
"io"
"net/http"
"os"
"strconv"
"github.com/NyaaPantsu/nyaa/config"
"github.com/NyaaPantsu/nyaa/models/torrents"
"github.com/gin-gonic/gin"
)
// DownloadTorrent : Controller for downloading a torrent
func DownloadTorrent(c *gin.Context) {
hash := c.Param("hash")
if hash == "" && len(config.Get().Torrents.FileStorage) == 0 {
//File not found, send 404
c.AbortWithError(http.StatusNotFound, errors.New("File not found"))
return
}
//Check if file exists and open
Openfile, err := os.Open(fmt.Sprintf("%s%c%s.torrent", config.Get().Torrents.FileStorage, os.PathSeparator, hash))
if err != nil {
//File not found, send 404
c.AbortWithError(http.StatusNotFound, errors.New("File not found"))
return
}
defer Openfile.Close() //Close after function return
//Get the file size
FileStat, _ := Openfile.Stat() //Get info from file
FileSize := strconv.FormatInt(FileStat.Size(), 10) //Get file size as a string
torrent, err := torrents.FindRawByHash(hash)
if err != nil {
//File not found, send 404
c.AbortWithError(http.StatusNotFound, errors.New("File not found"))
return
}
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s.torrent\"", torrent.Name))
c.Header("Content-Type", "application/x-bittorrent")
c.Header("Content-Length", FileSize)
//Send the file
// We reset the offset to 0
Openfile.Seek(0, 0)
io.Copy(c.Writer, Openfile) //'Copy' the file to the client
}