github.com/xraypb/Xray-core@v1.8.1/infra/conf/cfgcommon/duration/duration.go (about)

     1  package duration
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"time"
     7  )
     8  
     9  type Duration int64
    10  
    11  func (d *Duration) MarshalJSON() ([]byte, error) {
    12  	dr := time.Duration(*d)
    13  	return json.Marshal(dr.String())
    14  }
    15  
    16  func (d *Duration) UnmarshalJSON(b []byte) error {
    17  	var v interface{}
    18  	if err := json.Unmarshal(b, &v); err != nil {
    19  		return err
    20  	}
    21  	switch value := v.(type) {
    22  	case string:
    23  		var err error
    24  		dr, err := time.ParseDuration(value)
    25  		if err != nil {
    26  			return err
    27  		}
    28  		*d = Duration(dr)
    29  		return nil
    30  	default:
    31  		return fmt.Errorf("invalid duration: %v", v)
    32  	}
    33  }