github.com/sacloud/iaas-api-go@v1.12.0/types/result.go (about)

     1  // Copyright 2022-2023 The sacloud/iaas-api-go 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 types
    16  
    17  import "encoding/json"
    18  
    19  // APIResult APIからの戻り値"Success"の別表現
    20  //
    21  // Successにはbool以外にも"Accepted"などの文字列が返ることがある(例:アプライアンス)
    22  // このためAPIResultでUnmarshalJSONを実装してラップする
    23  type APIResult int
    24  
    25  const (
    26  	// ResultUnknown 不明
    27  	ResultUnknown APIResult = iota
    28  	// ResultSuccess 成功
    29  	ResultSuccess
    30  	// ResultAccepted 受付成功
    31  	ResultAccepted
    32  	// ResultFailed 失敗
    33  	ResultFailed
    34  )
    35  
    36  // UnmarshalJSON bool/string混在型に対応するためのUnmarshalJSON実装
    37  func (r *APIResult) UnmarshalJSON(data []byte) error {
    38  	*r = ResultUnknown
    39  
    40  	// try bool
    41  	var b bool
    42  	if err := json.Unmarshal(data, &b); err != nil {
    43  		// try string
    44  		var s string
    45  		if err := json.Unmarshal(data, &s); err != nil {
    46  			return err
    47  		}
    48  
    49  		if s == "Accepted" {
    50  			*r = ResultAccepted
    51  		}
    52  		return nil
    53  	}
    54  
    55  	if b {
    56  		*r = ResultSuccess
    57  	} else {
    58  		*r = ResultFailed
    59  	}
    60  	return nil
    61  }