ipfs-node-pin/ipfsnodepin/writer.go

52 lines
1.5 KiB
Go
Raw Permalink Normal View History

2024-01-08 11:25:24 +00:00
package ipfsnodepin
import (
"fmt"
"io"
"mime/multipart"
"net/textproto"
"net/url"
"strings"
)
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)
encodedName := url.QueryEscape(name)
h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, encodedName))
h.Set("Content-Type", "application/x-directory")
return w.CreatePart(h)
}
func (w *IpfsMultipartWriter) CreateIpfsFilePart(name string) (io.Writer, error) {
h := make(textproto.MIMEHeader)
encodedName := url.QueryEscape(name)
h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, escapeQuotes(encodedName)))
h.Set("Content-Type", "application/octet-stream")
return w.CreatePart(h)
}
func (w *IpfsMultipartWriter) CreateIpfsAbsFilePart(name, absPath string) (io.Writer, error) {
h := make(textproto.MIMEHeader)
encodedName := url.QueryEscape(name)
h.Set("AbsPath", absPath)
h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, escapeQuotes(encodedName)))
h.Set("Content-Type", "application/octet-stream")
return w.CreatePart(h)
}