gosimplenpm/internal/handler/tar.go

59 lines
1.8 KiB
Go
Raw Permalink Normal View History

package handler
import (
"bytes"
2023-12-25 08:56:48 +00:00
"fmt"
2023-11-25 02:17:09 +00:00
"gosimplenpm/internal/config"
"gosimplenpm/internal/storage"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/gorilla/mux"
2023-06-30 19:06:46 +00:00
"github.com/sirupsen/logrus"
)
2023-12-25 08:56:48 +00:00
func PackageTarGet(lg *logrus.Logger, cfg config.Config, stg storage.Storage) http.HandlerFunc {
2023-06-30 19:06:46 +00:00
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
2023-06-30 19:06:46 +00:00
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"]
2023-12-25 08:56:48 +00:00
tarFileNameWithScope, _ := url.PathUnescape(escapedName)
2023-06-30 19:06:46 +00:00
lg.WithFields(logrus.Fields{
"function": "get-tar",
2023-12-25 08:56:48 +00:00
}).Debugf("Tarfile name => %s\n", tarFileNameWithScope)
2023-12-25 08:56:48 +00:00
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)
2023-06-30 19:06:46 +00:00
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
2023-06-30 19:06:46 +00:00
// 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)))
}
}