github.com/cnotch/ipchub@v1.1.0/provider/route/json.go (about)

     1  // Copyright (c) 2019,CAOHONGJU All rights reserved.
     2  // Use of this source code is governed by a MIT-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package route
     6  
     7  import (
     8  	"encoding/json"
     9  	"fmt"
    10  	"io/ioutil"
    11  	"os"
    12  	"path/filepath"
    13  
    14  	"github.com/cnotch/ipchub/utils"
    15  )
    16  
    17  // JSON json 提供者
    18  var JSON = &jsonProvider{}
    19  
    20  type jsonProvider struct {
    21  	filePath string
    22  }
    23  
    24  func (p *jsonProvider) Name() string {
    25  	return "json"
    26  }
    27  
    28  func (p *jsonProvider) Configure(config map[string]interface{}) error {
    29  	path, ok := config["file"]
    30  	if ok {
    31  		switch v := path.(type) {
    32  		case string:
    33  			p.filePath = v
    34  		default:
    35  			return fmt.Errorf("invalid route table config, file attr: %v", path)
    36  		}
    37  	} else {
    38  		p.filePath = "routetable.json"
    39  	}
    40  
    41  	if !filepath.IsAbs(p.filePath) {
    42  		exe, err := os.Executable()
    43  		if err != nil {
    44  			return err
    45  		}
    46  		p.filePath = filepath.Join(filepath.Dir(exe), p.filePath)
    47  	}
    48  
    49  	return nil
    50  }
    51  
    52  func (p *jsonProvider) LoadAll() ([]*Route, error) {
    53  	path := p.filePath
    54  	if _, err := os.Stat(path); err != nil {
    55  		if os.IsNotExist(err) {
    56  			return nil, nil
    57  		}
    58  		return nil, err
    59  	}
    60  
    61  	// 从文件读
    62  	b, err := ioutil.ReadFile(path)
    63  	if err != nil {
    64  		return nil, err
    65  	}
    66  
    67  	var routes []*Route
    68  	if err := json.Unmarshal(b, &routes); err != nil {
    69  		return nil, err
    70  	}
    71  
    72  	return routes, nil
    73  }
    74  
    75  func (p *jsonProvider) Flush(full []*Route, saves []*Route, removes []*Route) error {
    76  	return utils.EncodeJSONFile(p.filePath, full)
    77  }