Skip to content

Instantly share code, notes, and snippets.

@monirz
Created June 13, 2022 04:26
Show Gist options
  • Save monirz/b79a79a87576b354db2c4459b470e8fc to your computer and use it in GitHub Desktop.
Save monirz/b79a79a87576b354db2c4459b470e8fc to your computer and use it in GitHub Desktop.
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
}
//set api key and secret api key in header
buffer := &bytes.Buffer{}
writer := multipart.NewWriter(buffer)
log.Println(header.Filename)
fw, err := writer.CreateFormFile("file", header.Filename)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Copy the file data to the writer,
// which will close the writer (deferred)
n, err := io.Copy(fw, file)
log.Println("size ", n)
writer.Close()
m := &sync.Mutex{}
go func(writer *multipart.Writer, body *bytes.Buffer, m *sync.Mutex) {
b, err := s.makePostRequestToPinata(writer, body)
if err != nil {
log.Println(err)
}
m.Lock()
log.Println(string(b))
// pinataResp <- b
m.Unlock()
}(writer, buffer, m)
//make post request to pinata
//write response body to response
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"message": "success, file is being uploaded"}`))
}
func (s *Server) makePostRequestToPinata(writer *multipart.Writer, body *bytes.Buffer) ([]byte, error) {
//create request
client := &http.Client{
// Timeout: 30 * time.Second,
}
req, err := http.NewRequest("POST", s.Config.PinataBaseURL+s.Config.PinataUploadEndPoint, bytes.NewReader(body.Bytes()))
if err != nil {
return nil, 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 {
return nil, err
}
defer resp.Body.Close()
//read response body
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return b, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment