github.com/jbking/gohan@v0.0.0-20151217002006-b41ccf1c2a96/cli/client/cache.go (about)

     1  // Copyright (C) 2015 NTT Innovation Institute, Inc.
     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
    12  // implied.
    13  // See the License for the specific language governing permissions and
    14  // limitations under the License.
    15  
    16  package client
    17  
    18  import (
    19  	"encoding/json"
    20  	"io/ioutil"
    21  	"os"
    22  	"time"
    23  
    24  	"github.com/cloudwan/gohan/schema"
    25  )
    26  
    27  // Cache ...
    28  type Cache struct {
    29  	Expire  time.Time
    30  	Schemas []*schema.Schema
    31  }
    32  
    33  func (gohanClientCLI *GohanClientCLI) getCachedSchemas() ([]*schema.Schema, error) {
    34  	rawCache, err := ioutil.ReadFile(gohanClientCLI.opts.cachePath)
    35  	if err != nil {
    36  		return gohanClientCLI.getSchemas()
    37  	}
    38  	cache := Cache{}
    39  	err = json.Unmarshal(rawCache, &cache)
    40  	if err != nil {
    41  		return gohanClientCLI.getSchemas()
    42  	}
    43  	if time.Now().After(cache.Expire) {
    44  		return gohanClientCLI.getSchemas()
    45  	}
    46  	return cache.Schemas, nil
    47  }
    48  
    49  func (gohanClientCLI *GohanClientCLI) setCachedSchemas() error {
    50  	cache := Cache{
    51  		Expire:  time.Now().Add(gohanClientCLI.opts.cacheTimeout),
    52  		Schemas: gohanClientCLI.schemas,
    53  	}
    54  	rawCache, _ := json.Marshal(cache)
    55  	err := ioutil.WriteFile(gohanClientCLI.opts.cachePath, rawCache, os.ModePerm)
    56  	if err != nil {
    57  		return err
    58  	}
    59  	return nil
    60  }