func StoreResponseFile(path string, resp []Response) error { sort.Sort(Responses(resp)) buf := new(bytes.Buffer) if err := toml.NewEncoder(buf).Encode(responses{resp}); err != nil { return err } if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { return err } f, err := os.Create(path) if err != nil { return err } defer f.Close() _, err = f.Write(buf.Bytes()) if err != nil { return err } return nil }
// saveToFile saves the Config in the file named path. This is a helper method // for generating sample configuration files. func (c *Config) saveToFile(path string) error { var data []byte switch filepath.Ext(path) { case ".json": d, err := json.MarshalIndent(c, "", "\t") // use tab indent to make it human friendly if err != nil { return err } data = d case ".yml": d, err := yaml.Marshal(c) if err != nil { return err } data = d case ".toml": b := &bytes.Buffer{} err := toml.NewEncoder(b).Encode(c) if err != nil { return err } data = b.Bytes() } return ioutil.WriteFile(path, data, 0600) }
func (c *Config) String() string { var b bytes.Buffer e := toml.NewEncoder(&b) e.Indent = " " e.Encode(c) return b.String() }
func (c *Config) CreateConfig() error { var yahooConfig YahooConfig fmt.Print("Input YahooToken: ") yahooConfig.Token = c.scan() var slackConfig SlackConfig fmt.Print("Input SlackToken: ") slackConfig.Token = c.scan() fmt.Print("Input SlackChannel: ") slackConfig.Channel = c.scan() fmt.Print("Input SlackNDaysAgo: ") nDaysAgo, err := strconv.Atoi(c.scan()) if err != nil { return err } slackConfig.NDaysAgo = nDaysAgo var generalConfig GeneralConfig fmt.Print("Input Upload Filename (.gif): ") generalConfig.Filename = c.scan() c.Yahoo = yahooConfig c.Slack = slackConfig c.General = generalConfig var buffer bytes.Buffer encoder := toml.NewEncoder(&buffer) if err := encoder.Encode(c); err != nil { return err } ioutil.WriteFile(configFile, []byte(buffer.String()), 0644) return nil }
func Toml(w http.ResponseWriter, r *http.Request) { buf, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, err.Error(), 500) return } mib := conf.MIB{} err = json.Unmarshal(buf, &mib) if err != nil { http.Error(w, err.Error(), 500) return } meta := &struct{ Name string }{} err = json.Unmarshal(buf, meta) if err != nil { http.Error(w, err.Error(), 500) return } toToml := struct { MIBs map[string]conf.MIB }{MIBs: map[string]conf.MIB{meta.Name: mib}} toml.NewEncoder(w).Encode(toToml) }
func StorePolynomialFile(path string, pols []Polynomial) error { sort.Sort(Polynomials(pols)) buf := new(bytes.Buffer) if err := toml.NewEncoder(buf).Encode(polynomials{pols}); err != nil { return err } if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { return err } f, err := os.Create(path) if err != nil { return err } defer f.Close() _, err = f.Write(buf.Bytes()) if err != nil { return err } return nil }
func (c *Config) Marshal() []byte { var buf bytes.Buffer if err := toml.NewEncoder(&buf).Encode(c); err != nil { panic(err) } return buf.Bytes() }
func TestLoadQuery(t *testing.T) { queries := &Queries{} for i := 0; i < 10; i++ { query := Query{ Name: fmt.Sprintf("name_%d", i+1), SQL: fmt.Sprintf("sql_%d", i+1), } queries.Query = append(queries.Query, query) } tempFile, err := ioutil.TempFile("", utils.GetAppName()+"-test") if err != nil { t.Errorf("failed to create the temp file: %s", err.Error()) } if err := toml.NewEncoder(tempFile).Encode(queries); err != nil { t.Errorf("failed to create the toml file: %s", err.Error()) } tempFile.Sync() tempFile.Close() defer os.Remove(tempFile.Name()) query, err := LoadQuery(tempFile.Name()) if err != nil { t.Errorf("query file load error: %s", err.Error()) } if !reflect.DeepEqual(queries, query) { t.Errorf("query data not match: %+v/%+v", queries, query) } }
func create_config_files(nr int, outputDir string) { quaggaConfigList := make([]*QuaggaConfig, 0) gobgpConf := config.Bgp{} gobgpConf.Global.Config.As = 65000 gobgpConf.Global.Config.RouterId = "192.168.255.1" for i := 1; i < nr+1; i++ { c := config.Neighbor{} c.Config.PeerAs = 65000 + uint32(i) c.Config.NeighborAddress = fmt.Sprintf("10.0.0.%d", i) c.Config.AuthPassword = fmt.Sprintf("hoge%d", i) gobgpConf.Neighbors = append(gobgpConf.Neighbors, c) q := NewQuaggaConfig(i, &gobgpConf.Global, &c, net.ParseIP("10.0.255.1")) quaggaConfigList = append(quaggaConfigList, q) os.Mkdir(fmt.Sprintf("%s/q%d", outputDir, i), 0755) err := ioutil.WriteFile(fmt.Sprintf("%s/q%d/bgpd.conf", outputDir, i), q.Config().Bytes(), 0644) if err != nil { log.Fatal(err) } } var buffer bytes.Buffer encoder := toml.NewEncoder(&buffer) encoder.Encode(gobgpConf) err := ioutil.WriteFile(fmt.Sprintf("%s/gobgpd.conf", outputDir), buffer.Bytes(), 0644) if err != nil { log.Fatal(err) } }
func specAction(c *cli.Context) { ec := &config.ExtensionConfig{ Name: "nginx", ConfigPath: "/etc/conf/nginx.conf", PidPath: "/etc/conf/nginx.pid", BackendOverrideAddress: "", } if err := config.SetConfigDefaults(ec); err != nil { log.Fatal(err) } cfg := &config.Config{ ListenAddr: ":8080", DockerURL: "unix:///var/run/docker.sock", EnableMetrics: true, Extensions: []*config.ExtensionConfig{ ec, }, } if err := toml.NewEncoder(os.Stdout).Encode(cfg); err != nil { log.Fatal(err) } }
func (s *TomlSuite) TestParse(c *C) { type Nested struct { Parent string `toml:"parent"` } type TestConfig struct { FileName string `toml:"file_name"` Count int `toml:"count"` Child Nested `toml:"child"` } config := TestConfig{ FileName: "test.me", Count: 10, Child: Nested{ Parent: "parent", }, } file, err := ioutil.TempFile("", "test") c.Assert(err, IsNil) defer func() { _ = file.Close() }() err = toml.NewEncoder(file).Encode(config) c.Assert(err, IsNil) // let's confirm that we can parse the data again config2 := TestConfig{} err = parseToml(file.Name(), &config2) c.Assert(err, IsNil) c.Assert(config2, DeepEquals, config) }
func StoreModelFile(path string, mods []Model) error { sort.Sort(Models(mods)) buf := new(bytes.Buffer) if err := toml.NewEncoder(buf).Encode(models{mods}); err != nil { return err } if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { return err } f, err := os.Create(path) if err != nil { return err } defer f.Close() _, err = f.Write(buf.Bytes()) if err != nil { return err } return nil }
func AppendDeployment(d Deployment, initIfMissing bool) (DeploymentConfig, error) { f, err := os.Open(path) if err != nil && initIfMissing { f, err = os.Create(path) } f.Close() config, err := ReadDeploymentConfig() if err != nil { return DeploymentConfig{}, err } if config.Deployments == nil { config.Deployments = make(map[string]Deployment) } config.Deployments[d.Id] = d f, _ = os.Create(path) encoder := toml.NewEncoder(f) err = encoder.Encode(config) if err != nil { return DeploymentConfig{}, err } return config, nil }
// TestConfig creates config with all files in root directory func TestConfig(rootDir string) string { cfg := NewConfig() cfg.Common.Logfile = filepath.Join(rootDir, "go-carbon.log") cfg.Whisper.DataDir = rootDir cfg.Whisper.SchemasFilename = filepath.Join(rootDir, "schemas.conf") // cfg.Whisper.Aggregation = filepath.Join(rootDir, "aggregation.conf") configFile := filepath.Join(rootDir, "go-carbon.conf") buf := new(bytes.Buffer) encoder := toml.NewEncoder(buf) encoder.Indent = "" if err := encoder.Encode(cfg); err != nil { return configFile } ioutil.WriteFile(cfg.Whisper.SchemasFilename, []byte(` [default] priority = 1 pattern = .* retentions = 60:43200,3600:43800`), 0644) ioutil.WriteFile(configFile, buf.Bytes(), 0644) return configFile }
func (dbConf DBConf) Write(w io.Writer) error { encoder := toml.NewEncoder(w) if err := encoder.Encode(dbConf); err != nil { return err } return nil }
// saveCurrentState saves the current running turtle apps. func saveCurrentState() error { // Create a new state value. var s state // Get all apps. curApps := apps.Apps() for _, app := range curApps { // Skip if not running. if !app.IsRunning() { continue } // Add the app name to the running apps slice. s.RunningApps = append(s.RunningApps, app.Name()) } // Encode the state value to TOML. buf := new(bytes.Buffer) err := toml.NewEncoder(buf).Encode(&s) if err != nil { return fmt.Errorf("failed to encode turtle state value to toml: %v", err) } // Write the result to the app settings file. err = ioutil.WriteFile(config.Config.StateFilePath(), buf.Bytes(), 0600) if err != nil { return fmt.Errorf("failed to save turtle state value: %v", err) } return nil }
// Run parses and prints the current config loaded. func (cmd *PrintConfigCommand) Run(args ...string) error { // Parse command flags. fs := flag.NewFlagSet("", flag.ContinueOnError) configPath := fs.String("config", "", "") fs.Usage = func() { fmt.Fprintln(cmd.Stderr, printConfigUsage) } if err := fs.Parse(args); err != nil { return err } // Parse config from path. config, err := cmd.parseConfig(*configPath) if err != nil { return fmt.Errorf("parse config: %s", err) } // Apply any environment variables on top of the parsed config if err := config.ApplyEnvOverrides(); err != nil { return fmt.Errorf("apply env config: %v", err) } // Validate the configuration. if err := config.Validate(); err != nil { return fmt.Errorf("%s. To generate a valid configuration file run `influxd config > influxdb.generated.conf`", err) } toml.NewEncoder(cmd.Stdout).Encode(config) fmt.Fprint(cmd.Stdout, "\n") return nil }
func StorePAZFile(path string, filters []PAZ) error { sort.Sort(PAZs(filters)) buf := new(bytes.Buffer) if err := toml.NewEncoder(buf).Encode(pazs{filters}); err != nil { return err } if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { return err } f, err := os.Create(path) if err != nil { return err } defer f.Close() _, err = f.Write(buf.Bytes()) if err != nil { return err } return nil }
// Run parses and prints the current config loaded. func (cmd *PrintConfigCommand) Run(args ...string) error { // Parse command flags. fs := flag.NewFlagSet("", flag.ContinueOnError) configPath := fs.String("config", "", "") hostname := fs.String("hostname", "", "") fs.Usage = func() { fmt.Fprintln(cmd.Stderr, printConfigUsage) } if err := fs.Parse(args); err != nil { return err } // Parse config from path. config, err := cmd.parseConfig(*configPath) if err != nil { return fmt.Errorf("parse config: %s", err) } // Override config properties. if *hostname != "" { config.Meta.Hostname = *hostname } toml.NewEncoder(cmd.Stdout).Encode(config) fmt.Fprint(cmd.Stdout, "\n") return nil }
func main() { b := config.Bgp{ Global: config.Global{ Config: config.GlobalConfig{ As: 12332, RouterId: "10.0.0.1", }, }, Neighbors: []config.Neighbor{ config.Neighbor{ Config: config.NeighborConfig{ PeerAs: 12333, AuthPassword: "******", NeighborAddress: "192.168.177.33", }, AfiSafis: []config.AfiSafi{ config.AfiSafi{AfiSafiName: "ipv4-unicast"}, config.AfiSafi{AfiSafiName: "ipv6-unicast"}, }, ApplyPolicy: config.ApplyPolicy{ Config: config.ApplyPolicyConfig{ ImportPolicyList: []string{"pd1"}, DefaultImportPolicy: config.DEFAULT_POLICY_TYPE_ACCEPT_ROUTE, }, }, }, config.Neighbor{ Config: config.NeighborConfig{ PeerAs: 12334, AuthPassword: "******", NeighborAddress: "192.168.177.32", }, }, config.Neighbor{ Config: config.NeighborConfig{ PeerAs: 12335, AuthPassword: "******", NeighborAddress: "192.168.177.34", }, }, }, } var buffer bytes.Buffer encoder := toml.NewEncoder(&buffer) err := encoder.Encode(b) if err != nil { panic(err) } err = encoder.Encode(policy()) if err != nil { panic(err) } fmt.Printf("%v\n", buffer.String()) }
// Set persists a configuration // in a .focus file inside the project folder func (c *Conf) Set(pwd string) error { buf := new(bytes.Buffer) if err := toml.NewEncoder(buf).Encode(c); err != nil { return errwrap.Wrapf("toml encoding error", err) } err := ioutil.WriteFile(pwd+confFile, buf.Bytes(), 0644) return err }
// Flush writes the config to disk func (c *Config) Flush() { file, _ := os.Create(confPath) encoder := toml.NewEncoder(file) if err := encoder.Encode(c); err != nil { panic(err) } }
func printConfigTemplate() { enc := toml.NewEncoder(os.Stdout) if err := enc.Encode(config); err != nil { // Shouldn't ever happen, so make some noise panic(err) } fmt.Fprintln(os.Stdout) }
//PrintConfig : dumps config to stdout func (c *Config) PrintConfig() { buf := new(bytes.Buffer) err := toml.NewEncoder(buf).Encode(c) if err != nil { logger.Fatal("Config Encode error %v", err) } fmt.Println(buf.String()) }
// Save writes the config to file(s) func (gf *GeneralConfig) Save() error { buf := new(bytes.Buffer) cfgPath := gf.Path + "/" + gf.Name + ".conf" if err := toml.NewEncoder(buf).Encode(gf); err != nil { return err } return ioutil.WriteFile(cfgPath, buf.Bytes(), 0644) }
func load(obj interface{}, conf map[string]interface{}) error { buf := new(bytes.Buffer) if err := toml.NewEncoder(buf).Encode(conf); err != nil { return err } _, err := toml.Decode(buf.String(), obj) return err }
func (c *Config) String() string { var b bytes.Buffer err := toml.NewEncoder(&b).Encode(c) if err != nil { return err.Error() } return b.String() }
func encodeConf(conf map[string]interface{}) string { b := new(bytes.Buffer) if err := toml.NewEncoder(b).Encode(conf); err != nil { // Usually not reached because conf is decoded from toml panic(err) } return b.String() }
func write(w io.Writer, t interface{}) error { if t == nil { _, err := fmt.Fprint(w, "\n") if err != nil { return err } } else { switch t.(type) { case int64: _, err := fmt.Fprintf(w, "%d\n", t) if err != nil { return err } case string: _, err := fmt.Fprintf(w, "\"%s\"\n", t) if err != nil { return err } case []map[string]interface{}: e := toml.NewEncoder(w) s, _ := t.([]map[string]interface{}) for _, v := range s { err := e.Encode(v) if err != nil { return err } } case []interface{}: s, _ := t.([]interface{}) for _, v := range s { err := write(w, v) if err != nil { return err } } default: e := toml.NewEncoder(os.Stdout) err := e.Encode(t) if err != nil { return err } } } return nil }
// EncodeConfigFile will take an AdminServer instance and convert it to a TOML-formatted byte buffer. // This TOML byte buffer can then be serialized to disk as a configuration file. func (cfg AdminServer) EncodeConfigFile() *bytes.Buffer { var buf bytes.Buffer enc := toml.NewEncoder(&buf) err := enc.Encode(cfg) if err != nil { panic(fmt.Errorf("Unable to encode wlsrest configuration: %s \n", err)) } return &buf }