Skip to content

Instantly share code, notes, and snippets.

@monirz
Created June 13, 2022 07:07
Show Gist options
  • Save monirz/1656fae96ae0ca8b62b68ab64e368be8 to your computer and use it in GitHub Desktop.
Save monirz/1656fae96ae0ca8b62b68ab64e368be8 to your computer and use it in GitHub Desktop.
package handler
import (
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"runtime"
)
func (s *Server) uploadFileHandler(w http.ResponseWriter, r *http.Request) {
// Get the file from the request
err := r.ParseMultipartForm(10 << 20)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
file, header, err := r.FormFile("file")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
pipeOut, pipeIn := io.Pipe()
writer := multipart.NewWriter(pipeIn)
go func() {
client := &http.Client{
// Timeout: 30 * time.Second,
}
req, err := http.NewRequest("POST", s.Config.PinataBaseURL+s.Config.PinataUploadEndPoint, pipeOut)
if err != nil {
log.Println(err)
}
// req.Header.Set("Content-Type", header.Header.Get("Content-Type"))
req.Header.Set("pinata_api_key", s.Config.PinataAPIKey)
req.Header.Set("pinata_secret_api_key", s.Config.PinataSecretAPIKey)
req.Header.Set("Content-Type", writer.FormDataContentType())
resp, err := client.Do(req)
if err != nil {
log.Println(err)
}
defer resp.Body.Close()
//read response body
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println(err)
}
log.Println(string(b))
}()
part, err := writer.CreateFormFile("file", header.Filename)
_, err = io.Copy(part, file)
check(err)
check(writer.Close())
check(pipeIn.Close())
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"message": "success, file is being uploaded"}`))
}
func check(err error) {
_, file, line, _ := runtime.Caller(1)
if err != nil {
log.Fatalf("Fatal from <%s:%d>\nError:%s", file, line, err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment