github.com/simpleiot/simpleiot@v0.18.3/client/send-file.go (about)

     1  package client
     2  
     3  // FIXME could probably find a better place for this file ...
     4  
     5  import (
     6  	"errors"
     7  	"net/http"
     8  	"strings"
     9  	"time"
    10  
    11  	"github.com/nats-io/nats.go"
    12  )
    13  
    14  // Note, this file is still in the api package (vs nats) as http bloats a build, and not
    15  // all edge devices need http.
    16  
    17  // Companion file in nats/file.go
    18  
    19  // NatsSendFileFromHTTP fetchs a file using http and sends via nats. Callback provides % complete (0-100).
    20  func NatsSendFileFromHTTP(nc *nats.Conn, deviceID string, url string, callback func(int)) error {
    21  	var netClient = &http.Client{
    22  		Timeout: time.Second * 60,
    23  	}
    24  
    25  	resp, err := netClient.Get(url)
    26  
    27  	if err != nil {
    28  		return err
    29  	}
    30  
    31  	defer resp.Body.Close()
    32  
    33  	if resp.StatusCode != http.StatusOK {
    34  		return errors.New("Error reading file over http: " + resp.Status)
    35  	}
    36  
    37  	urlS := strings.Split(url, "/")
    38  	if len(urlS) < 2 {
    39  		return errors.New("Error parsing URL")
    40  	}
    41  	name := urlS[len(urlS)-1]
    42  
    43  	return SendFile(nc, deviceID, resp.Body, name, func(bytesTx int) {
    44  		callback(bytesTx)
    45  	})
    46  }