2020-11-08 17:19:25 +00:00
|
|
|
package http
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/anacrolix/missinggo/v2/filecache"
|
2021-03-01 16:43:28 +00:00
|
|
|
"github.com/distribyted/distribyted"
|
|
|
|
"github.com/distribyted/distribyted/config"
|
2021-11-16 12:13:58 +00:00
|
|
|
"github.com/distribyted/distribyted/torrent"
|
2020-11-08 17:19:25 +00:00
|
|
|
"github.com/gin-contrib/static"
|
|
|
|
"github.com/gin-gonic/gin"
|
2021-03-10 09:54:56 +00:00
|
|
|
"github.com/rs/zerolog/log"
|
2020-11-08 17:19:25 +00:00
|
|
|
"github.com/shurcooL/httpfs/html/vfstemplate"
|
|
|
|
)
|
|
|
|
|
2021-11-16 12:13:58 +00:00
|
|
|
func New(fc *filecache.Cache, ss *torrent.Stats, s *torrent.Service, ch *config.Handler, port int) error {
|
2020-11-08 17:19:25 +00:00
|
|
|
gin.SetMode(gin.ReleaseMode)
|
|
|
|
r := gin.New()
|
|
|
|
r.Use(gin.Recovery())
|
|
|
|
r.Use(gin.ErrorLogger())
|
|
|
|
|
|
|
|
assets := distribyted.NewBinaryFileSystem(distribyted.HttpFS, "/assets")
|
|
|
|
r.Use(static.Serve("/assets", assets))
|
|
|
|
t, err := vfstemplate.ParseGlob(distribyted.HttpFS, nil, "/templates/*")
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("error parsing html: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
r.SetHTMLTemplate(t)
|
|
|
|
|
|
|
|
r.GET("/", indexHandler)
|
|
|
|
r.GET("/routes", routesHandler(ss))
|
2020-11-09 10:33:19 +00:00
|
|
|
|
2020-11-08 17:19:25 +00:00
|
|
|
api := r.Group("/api")
|
|
|
|
{
|
|
|
|
api.GET("/status", apiStatusHandler(fc, ss))
|
|
|
|
api.GET("/routes", apiRoutesHandler(ss))
|
2021-11-16 12:13:58 +00:00
|
|
|
api.POST("/routes/:route/torrent", apiAddTorrentHandler(s))
|
|
|
|
api.DELETE("/routes/:route/torrent/:torrent_hash", apiDelTorrentHandler(s))
|
|
|
|
|
2020-11-08 17:19:25 +00:00
|
|
|
}
|
|
|
|
|
2021-03-10 09:54:56 +00:00
|
|
|
log.Info().Str("host", fmt.Sprintf("0.0.0.0:%d", port)).Msg("starting webserver")
|
2020-11-08 17:19:25 +00:00
|
|
|
|
|
|
|
if err := r.Run(fmt.Sprintf(":%d", port)); err != nil {
|
|
|
|
return fmt.Errorf("error initializing server: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|