github.com/sacloud/libsacloud/v2@v2.32.3/helper/service/util.go (about) 1 // Copyright 2016-2022 The Libsacloud Authors 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 15 package service 16 17 import ( 18 "fmt" 19 "time" 20 21 "github.com/sacloud/libsacloud/v2/pkg/mapconv" 22 "github.com/sacloud/libsacloud/v2/pkg/size" 23 "github.com/sacloud/libsacloud/v2/sacloud" 24 ) 25 26 func HandleNotFoundError(err error, ignoreNotFoundError bool) error { 27 if ignoreNotFoundError && sacloud.IsNotFoundError(err) { 28 return nil // ignore: 404 not found 29 } 30 return err 31 } 32 33 func MonitorCondition(start, end time.Time) (*sacloud.MonitorCondition, error) { 34 e := end 35 if e.IsZero() { 36 e = time.Now() 37 } 38 39 s := start 40 if s.IsZero() { 41 s = e.Add(-1 * time.Hour) 42 } 43 if !(s.Unix() <= e.Unix()) { 44 return nil, fmt.Errorf("start(%s) or end(%s) is invalid", start.String(), end.String()) 45 } 46 return &sacloud.MonitorCondition{Start: s, End: e}, nil 47 } 48 49 func RequestConvertTo(source interface{}, dest interface{}) error { 50 decoder := &mapconv.Decoder{ 51 Config: &mapconv.DecoderConfig{ 52 TagName: "request", 53 FilterFuncs: map[string]mapconv.FilterFunc{ 54 "gb_to_mb": gbToMb, 55 }, 56 }, 57 } 58 return decoder.ConvertTo(source, dest) 59 } 60 61 func gbToMb(v interface{}) (interface{}, error) { 62 s, ok := v.(int) 63 if !ok { 64 return nil, fmt.Errorf("invalid size value: %v", v) 65 } 66 return size.GiBToMiB(s), nil 67 }