Custom multipart writer
All checks were successful
Create and publish a Docker image / build-and-push-image (push) Successful in 55s

This commit is contained in:
Alexandre Bruyant 2024-01-07 13:54:14 +01:00
parent f81ceeb17c
commit 17c3c51acb

45
main.go
View File

@ -10,6 +10,7 @@ import (
"net/textproto" "net/textproto"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"github.com/sethvargo/go-githubactions" "github.com/sethvargo/go-githubactions"
) )
@ -21,6 +22,37 @@ type AddResponse struct {
Size string Size string
} }
type IpfsMultipartWriter struct {
multipart.Writer
}
var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
func escapeQuotes(s string) string {
return quoteEscaper.Replace(s)
}
func NewIpfsMultipartWriter(w io.Writer) *IpfsMultipartWriter {
return &IpfsMultipartWriter{
Writer: *multipart.NewWriter(w),
}
}
func (w *IpfsMultipartWriter) CreateIpfsDirectoryPart(name string) (io.Writer, error) {
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, name))
h.Set("Content-Type", "application/x-directory")
return w.CreatePart(h)
}
func (w *IpfsMultipartWriter) CreateIpfsFilePart(absPath, name string) (io.Writer, error) {
h := make(textproto.MIMEHeader)
h.Set("AbsPath", absPath)
h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, escapeQuotes(name)))
h.Set("Content-Type", "application/octet-stream")
return w.CreatePart(h)
}
func main() { func main() {
githubactions.Infof("Checking inputs...") githubactions.Infof("Checking inputs...")
@ -65,18 +97,17 @@ func main() {
githubactions.Fatalf("Unable to create request: %v", err.Error()) githubactions.Fatalf("Unable to create request: %v", err.Error())
} }
mwriter := multipart.NewWriter(writer) mwriter := NewIpfsMultipartWriter(writer)
req.Header.Add("Content-Type", mwriter.FormDataContentType()) req.Header.Add("Content-Type", mwriter.FormDataContentType())
go func() { go func() {
defer mwriter.Close() defer mwriter.Close()
defer writer.Close() defer writer.Close()
h := make(textproto.MIMEHeader) w, err := mwriter.CreateIpfsDirectoryPart(path)
h.Set("Content-Disposition", if err != nil {
fmt.Sprintf(`form-data; name="file"; filename="%s"`, path)) githubactions.Fatalf("Unable to create root dir path: %v", fmt.Errorf("%w", err))
h.Set("Content-Type", "application/x-directory") }
mwriter.CreatePart(h)
err = filepath.Walk(path, func(innerPath string, info fs.FileInfo, err error) error { err = filepath.Walk(path, func(innerPath string, info fs.FileInfo, err error) error {
if err != nil { if err != nil {
@ -88,7 +119,7 @@ func main() {
} }
githubactions.Infof("Reading %v", innerPath) githubactions.Infof("Reading %v", innerPath)
w, err := mwriter.CreateFormFile("file", innerPath) w, err = mwriter.CreateFormFile("file", innerPath)
if err != nil { if err != nil {
return err return err
} }