Exemplo n.º 1
0
func main() {
	defaultPath, _ := os.Getwd()
	defaultFile := filepath.Join(defaultPath, "streamer.go")
	fullpath := flag.String("path", defaultFile, "Path to the include in the multipart data.")
	flag.Parse()

	ms := multipartstreamer.New()

	fmt.Println("Adding the file to the multipart writer")
	ms.WriteFile("file", *fullpath)
	reader := ms.GetReader()

	fmt.Println("Writing the multipart data to a file")
	file, _ := os.Create("streamtest")
	io.Copy(file, reader)
}
Exemplo n.º 2
0
// UploadFile makes a request to the API with a file.
//
// Requires the parameter to hold the file not be in the params.
// File should be a string to a file path, a FileBytes struct, or a FileReader struct.
func (bot *BotAPI) UploadFile(endpoint string, params map[string]string, fieldname string, file interface{}) (APIResponse, error) {
	ms := multipartstreamer.New()
	ms.WriteFields(params)

	switch f := file.(type) {
	case string:
		fileHandle, err := os.Open(f)
		if err != nil {
			return APIResponse{}, err
		}
		defer fileHandle.Close()

		fi, err := os.Stat(f)
		if err != nil {
			return APIResponse{}, err
		}

		ms.WriteReader(fieldname, fileHandle.Name(), fi.Size(), fileHandle)
	case FileBytes:
		buf := bytes.NewBuffer(f.Bytes)
		ms.WriteReader(fieldname, f.Name, int64(len(f.Bytes)), buf)
	case FileReader:
		if f.Size == -1 {
			data, err := ioutil.ReadAll(f.Reader)
			if err != nil {
				return APIResponse{}, err
			}
			buf := bytes.NewBuffer(data)

			ms.WriteReader(fieldname, f.Name, int64(len(data)), buf)

			break
		}

		ms.WriteReader(fieldname, f.Name, f.Size, f.Reader)
	default:
		return APIResponse{}, errors.New("bad file type")
	}

	req, err := http.NewRequest("POST", fmt.Sprintf(APIEndpoint, bot.Token, endpoint), nil)
	ms.SetupRequest(req)
	if err != nil {
		return APIResponse{}, err
	}

	res, err := bot.Client.Do(req)
	if err != nil {
		return APIResponse{}, err
	}
	defer res.Body.Close()

	bytes, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return APIResponse{}, err
	}

	if bot.Debug {
		log.Println(string(bytes[:]))
	}

	var apiResp APIResponse
	json.Unmarshal(bytes, &apiResp)

	return apiResp, nil
}