listobjects-N.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // +build ignore
  2. /*
  3. * Minio Go Library for Amazon S3 Compatible Cloud Storage
  4. * Copyright 2015-2017 Minio, Inc.
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. package main
  19. import (
  20. "fmt"
  21. "github.com/minio/minio-go"
  22. )
  23. func main() {
  24. // Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY, my-bucketname and my-prefixname
  25. // are dummy values, please replace them with original values.
  26. // Requests are always secure (HTTPS) by default. Set secure=false to enable insecure (HTTP) access.
  27. // This boolean value is the last argument for New().
  28. // New returns an Amazon S3 compatible client object. API compatibility (v2 or v4) is automatically
  29. // determined based on the Endpoint value.
  30. s3Client, err := minio.New("s3.amazonaws.com", "YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY", true)
  31. if err != nil {
  32. fmt.Println(err)
  33. return
  34. }
  35. // List 'N' number of objects from a bucket-name with a matching prefix.
  36. listObjectsN := func(bucket, prefix string, recursive bool, N int) (objsInfo []minio.ObjectInfo, err error) {
  37. // Create a done channel to control 'ListObjects' go routine.
  38. doneCh := make(chan struct{}, 1)
  39. // Free the channel upon return.
  40. defer close(doneCh)
  41. i := 1
  42. for object := range s3Client.ListObjects(bucket, prefix, recursive, doneCh) {
  43. if object.Err != nil {
  44. return nil, object.Err
  45. }
  46. i++
  47. // Verify if we have printed N objects.
  48. if i == N {
  49. // Indicate ListObjects go-routine to exit and stop
  50. // feeding the objectInfo channel.
  51. doneCh <- struct{}{}
  52. }
  53. objsInfo = append(objsInfo, object)
  54. }
  55. return objsInfo, nil
  56. }
  57. // List recursively first 100 entries for prefix 'my-prefixname'.
  58. recursive := true
  59. objsInfo, err := listObjectsN("my-bucketname", "my-prefixname", recursive, 100)
  60. if err != nil {
  61. fmt.Println(err)
  62. }
  63. // Print all the entries.
  64. fmt.Println(objsInfo)
  65. }