gosimplenpm/internal/handler/tar.go

59 lines
1.8 KiB
Go

package handler
import (
"bytes"
"fmt"
"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, stg storage.Storage) 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"]
tarFileNameWithScope, _ := url.PathUnescape(escapedName)
lg.WithFields(logrus.Fields{
"function": "get-tar",
}).Debugf("Tarfile name => %s\n", tarFileNameWithScope)
fmt.Printf("Tarfile name => %s\n", tarFileNameWithScope)
fragments := strings.Split(tarFileNameWithScope, "/")
tarFileName := fragments[len(fragments)-1]
// fragments := strings.Split(urlFileFragment, "-")
// versionFragment := fragments[len(fragments)-1]
// versionName := strings.Split(versionFragment, ".tgz")[0]
// fmt.Printf("Version name => %s\n", versionName)
fileAsString, err := stg.GetTarFromStore(packageName, tarFileName, 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)))
}
}