gosimplenpm/internal/handler/tar.go

51 lines
1.4 KiB
Go

package handler
import (
"bytes"
"gosimplenpm/internal/config"
"gosimplenpm/internal/storage"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
)
func PackageTarGet(lg *logrus.Logger, cfg config.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Sample output of npm view
// Public
// dist
// .tarball: https://registry.npmjs.org/react/-/react-18.2.0.tgz
// LocalHost
// dist
// .tarball: http://localhost:4000/@ookusanya/package1/-/package1-0.2.0.tgz
escapedName := mux.Vars(r)["name"]
packageName, _ := url.PathUnescape(escapedName)
lg.WithFields(logrus.Fields{
"function": "get-tar",
}).Debugf("Package name => %s\n", packageName)
escapedName = mux.Vars(r)["tar"]
tarFileName, _ := url.PathUnescape(escapedName)
lg.WithFields(logrus.Fields{
"function": "get-tar",
}).Debugf("Tarfile name => %s\n", tarFileName)
versionName := strings.Split(strings.Split(tarFileName, "-")[1], ".tgz")[0]
fileAsString, err := storage.GetTarFromStore(packageName, versionName, cfg.RepoDir, lg)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Sending the tar as a base64 string
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Length", strconv.Itoa(len([]byte(fileAsString))))
io.Copy(w, bytes.NewReader([]byte(fileAsString)))
}
}