printobj.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package printutils
  15. import (
  16. "fmt"
  17. "reflect"
  18. "yunion.io/x/jsonutils"
  19. )
  20. func PrintInterfaceList(data interface{}, total, offset, limit int, columns []string) {
  21. dataValue := reflect.ValueOf(data)
  22. if dataValue.Kind() != reflect.Slice {
  23. fmt.Println("Invalid list data")
  24. return
  25. }
  26. jsonList := make([]jsonutils.JSONObject, dataValue.Len())
  27. for i := 0; i < dataValue.Len(); i += 1 {
  28. jsonList[i] = jsonutils.Marshal(dataValue.Index(i).Interface())
  29. }
  30. if total == 0 {
  31. total = dataValue.Len()
  32. }
  33. list := &ListResult{
  34. Data: jsonList,
  35. Total: total,
  36. Limit: limit,
  37. Offset: offset,
  38. }
  39. PrintJSONList(list, columns)
  40. }
  41. func PrintInterfaceObject(obj interface{}) {
  42. PrintJSONObject(jsonutils.Marshal(obj))
  43. }