How to use Format method of config Package

Best Gauge code snippet using config.Format

config.go

Source:config.go Github

copy

Full Screen

...63			return runConfigGet(cli, opts)64		},65	}66	flags := cmd.Flags()67	flags.StringVarP(&opts.Format, "format", "f", "", "Format output")68	return cmd69}70type ConfigGetOptions struct {71	Format string72}73func runConfigGet(cli agentcli.Cli, opts ConfigGetOptions) error {74	// get generic client75	c, err := cli.Client().GenericClient()76	if err != nil {77		return err78	}79	// create dynamically config that can hold all remote known models80	// (not using local model registry that gives only locally available models)81	knownModels, err := c.KnownModels("config")82	if err != nil {83		return fmt.Errorf("getting registered models: %w", err)84	}85	config, err := client.NewDynamicConfig(knownModels)86	if err != nil {87		return fmt.Errorf("can't create all-config proto message dynamically due to: %w", err)88	}89	// retrieve data into config90	if err := c.GetConfig(config); err != nil {91		return fmt.Errorf("can't retrieve configuration due to: %v", err)92	}93	// handle data output94	format := opts.Format95	if len(format) == 0 {96		format = `yaml`97	}98	if err := formatAsTemplate(cli.Out(), format, config); err != nil {99		return err100	}101	return nil102}103func newConfigUpdateCommand(cli agentcli.Cli) *cobra.Command {104	var (105		opts ConfigUpdateOptions106	)107	cmd := &cobra.Command{108		Use:   "update",109		Short: "Update config in agent",110		Long:  "Update configuration in agent from file",111		Args:  cobra.MaximumNArgs(1),112		RunE: func(cmd *cobra.Command, args []string) error {113			return runConfigUpdate(cli, opts, args)114		},115	}116	flags := cmd.Flags()117	flags.StringVarP(&opts.Format, "format", "f", "", "Format output")118	flags.BoolVar(&opts.Replace, "replace", false, "Replaces all existing config")119	// TODO implement waitdone also for generic client120	// flags.BoolVar(&opts.WaitDone, "waitdone", false, "Waits until config update is done")121	// TODO implement transaction output when verbose is used122	// flags.BoolVarP(&opts.Verbose, "verbose", "v", false, "Show verbose output")123	flags.DurationVarP(&opts.Timeout, "timeout", "t",124		5*time.Minute, "Timeout for sending updated data")125	return cmd126}127type ConfigUpdateOptions struct {128	Format  string129	Replace bool130	// WaitDone bool131	// Verbose  bool132	Timeout time.Duration133}134func runConfigUpdate(cli agentcli.Cli, opts ConfigUpdateOptions, args []string) error {135	ctx, cancel := context.WithTimeout(context.Background(), opts.Timeout)136	defer cancel()137	// get input file138	if len(args) == 0 {139		return fmt.Errorf("missing file argument")140	}141	file := args[0]142	b, err := ioutil.ReadFile(file)143	if err != nil {144		return fmt.Errorf("reading file %s: %w", file, err)145	}146	// get generic client147	c, err := cli.Client().GenericClient()148	if err != nil {149		return err150	}151	// create dynamically config that can hold all remote known models152	// (not using local model registry that gives only locally available models)153	knownModels, err := c.KnownModels("config")154	if err != nil {155		return fmt.Errorf("getting registered models: %w", err)156	}157	config, err := client.NewDynamicConfig(knownModels)158	if err != nil {159		return fmt.Errorf("can't create all-config proto message dynamically due to: %w", err)160	}161	// filling dynamically created config with data from input file162	bj, err := yaml2.YAMLToJSON(b)163	if err != nil {164		return fmt.Errorf("converting to JSON: %w", err)165	}166	err = protojson.Unmarshal(bj, config)167	if err != nil {168		return fmt.Errorf("can't unmarshall input file data "+169			"into dynamically created config due to: %v", err)170	}171	logrus.Infof("loaded config :\n%s", config)172	// extracting proto messages from dynamically created config structure173	// (generic client wants single proto messages and not one big hierarchical config)174	configMessages, err := client.DynamicConfigExport(config)175	if err != nil {176		return fmt.Errorf("can't extract single configuration proto messages "+177			"from one big configuration proto message due to: %v", err)178	}179	// update/resync configuration180	if opts.Replace {181		if err := c.ResyncConfig(configMessages...); err != nil {182			return fmt.Errorf("resync failed: %v", err)183		}184	} else {185		req := c.ChangeRequest()186		req.Update(configMessages...)187		if err := req.Send(ctx); err != nil {188			return fmt.Errorf("send failed: %v", err)189		}190	}191	// handle configuration update result and command output192	format := opts.Format193	if len(format) == 0 {194		format = `{{.}}`195	}196	if err := formatAsTemplate(cli.Out(), format, "OK"); err != nil {197		return err198	}199	return nil200}201func newConfigDeleteCommand(cli agentcli.Cli) *cobra.Command {202	var (203		opts ConfigDeleteOptions204	)205	cmd := &cobra.Command{206		Use:   "delete",207		Short: "Delete config in agent",208		Long:  "Delete configuration in agent",209		Args:  cobra.MaximumNArgs(1),210		RunE: func(cmd *cobra.Command, args []string) error {211			return runConfigDelete(cli, opts, args)212		},213	}214	flags := cmd.Flags()215	flags.StringVarP(&opts.Format, "format", "f", "", "Format output")216	flags.BoolVar(&opts.WaitDone, "waitdone", false, "Waits until config update is done")217	flags.BoolVarP(&opts.Verbose, "verbose", "v", false, "Show verbose output")218	return cmd219}220type ConfigDeleteOptions struct {221	Format   string222	WaitDone bool223	Verbose  bool224}225func runConfigDelete(cli agentcli.Cli, opts ConfigDeleteOptions, args []string) error {226	ctx, cancel := context.WithCancel(context.Background())227	defer cancel()228	c, err := cli.Client().ConfiguratorClient()229	if err != nil {230		return err231	}232	if len(args) == 0 {233		return fmt.Errorf("missing file argument")234	}235	file := args[0]236	b, err := ioutil.ReadFile(file)237	if err != nil {238		return fmt.Errorf("reading file %s: %w", file, err)239	}240	var update = &configurator.Config{}241	bj, err := yaml2.YAMLToJSON(b)242	if err != nil {243		return fmt.Errorf("converting to JSON: %w", err)244	}245	err = protojson.Unmarshal(bj, update)246	if err != nil {247		return err248	}249	logrus.Infof("loaded config delete:\n%s", update)250	var data interface{}251	var header metadata.MD252	resp, err := c.Delete(ctx, &configurator.DeleteRequest{253		Delete:   update,254		WaitDone: opts.WaitDone,255	}, grpc.Header(&header))256	if err != nil {257		logrus.Warnf("delete failed: %v", err)258		data = err259	} else {260		data = resp261	}262	if opts.Verbose {263		logrus.Debugf("grpc header: %+v", header)264		if seqNum, ok := header["seqnum"]; ok {265			ref, _ := strconv.Atoi(seqNum[0])266			txns, err := cli.Client().SchedulerHistory(ctx, types.SchedulerHistoryOptions{267				SeqNum: ref,268			})269			if err != nil {270				logrus.Warnf("getting history for seqNum %d failed: %v", ref, err)271			} else {272				data = txns273			}274		}275	}276	format := opts.Format277	if len(format) == 0 {278		format = `{{.}}`279	}280	if err := formatAsTemplate(cli.Out(), format, data); err != nil {281		return err282	}283	return nil284}285func newConfigRetrieveCommand(cli agentcli.Cli) *cobra.Command {286	var (287		opts ConfigRetrieveOptions288	)289	cmd := &cobra.Command{290		Use:     "retrieve",291		Aliases: []string{"ret", "read", "dump"},292		Short:   "Retrieve currently running config",293		Args:    cobra.NoArgs,294		RunE: func(cmd *cobra.Command, args []string) error {295			return runConfigRetrieve(cli, opts)296		},297	}298	flags := cmd.Flags()299	flags.StringVarP(&opts.Format, "format", "f", "", "Format output")300	return cmd301}302type ConfigRetrieveOptions struct {303	Format string304}305func runConfigRetrieve(cli agentcli.Cli, opts ConfigRetrieveOptions) error {306	ctx, cancel := context.WithCancel(context.Background())307	defer cancel()308	c, err := cli.Client().ConfiguratorClient()309	if err != nil {310		return err311	}312	resp, err := c.Dump(ctx, &configurator.DumpRequest{})313	if err != nil {314		return err315	}316	format := opts.Format317	if len(format) == 0 {318		format = `yaml`319	}320	if err := formatAsTemplate(cli.Out(), format, resp.Dump); err != nil {321		return err322	}323	return nil324}325func newConfigWatchCommand(cli agentcli.Cli) *cobra.Command {326	var (327		opts ConfigWatchOptions328	)329	cmd := &cobra.Command{330		Use:     "watch",331		Aliases: []string{"notify", "subscribe"},332		Short:   "Watch events",333		Example: "Filter events by VPP interface name 'loop1'" +334			`{{.CommandPath}} config watch --filter='{"vpp_notification":{"interface":{"state":{"name":"loop1"}}}}'` +335			"" +336			"Filter events by VPP interface UPDOWN type" +337			`{{.CommandPath}} config watch --filter='{"vpp_notification":{"interface":{"type":"UPDOWN"}}}'`,338		Args: cobra.NoArgs,339		RunE: func(cmd *cobra.Command, args []string) error {340			return runConfigWatch(cli, opts)341		},342	}343	flags := cmd.Flags()344	flags.StringArrayVar(&opts.Filters, "filter", nil, "Filter(s) for notifications (multiple filters are used with AND operator). Value should be JSON data of configurator.Notification.")345	flags.StringVarP(&opts.Format, "format", "f", "", "Format output")346	return cmd347}348type ConfigWatchOptions struct {349	Format  string350	Filters []string351}352func runConfigWatch(cli agentcli.Cli, opts ConfigWatchOptions) error {353	ctx, cancel := context.WithCancel(context.Background())354	defer cancel()355	c, err := cli.Client().ConfiguratorClient()356	if err != nil {357		return err358	}359	filters, err := prepareNotifyFilters(opts.Filters)360	if err != nil {361		return fmt.Errorf("filters error: %w", err)362	}363	var nextIdx uint32364	stream, err := c.Notify(ctx, &configurator.NotifyRequest{365		Idx:     nextIdx,366		Filters: filters,367	})368	if err != nil {369		return err370	}371	format := opts.Format372	if len(format) == 0 {373		format = `------------------374 NOTIFICATION #{{.NextIdx}}375------------------376{{if .Notification.GetVppNotification}}Source: VPP377Value: {{protomulti .Notification.GetVppNotification}}378{{else if .Notification.GetLinuxNotification}}Source: LINUX379Value:  {{protomulti .Notification.GetLinuxNotification}}380{{else}}Source: {{printf "%T" .Notification.GetNotification}}381Value:  {{protomulti .Notification.GetNotification}}382{{end}}`383	}384	for {385		notif, err := stream.Recv()386		if err == io.EOF {387			break388		} else if err != nil {389			return err390		}391		logrus.Debugf("Notification[%d]: %v",392			notif.NextIdx-1, notif.Notification)393		nextIdx = notif.NextIdx394		if err := formatAsTemplate(cli.Out(), format, notif); err != nil {395			return err396		}397	}398	return nil399}400func prepareNotifyFilters(filters []string) ([]*configurator.Notification, error) {401	var list []*configurator.Notification402	for _, filter := range filters {403		notif := &configurator.Notification{}404		err := protojson.Unmarshal([]byte(filter), notif)405		if err != nil {406			return nil, err407		}408		list = append(list, notif)409	}410	return list, nil411}412func newConfigResyncCommand(cli agentcli.Cli) *cobra.Command {413	var (414		opts ConfigResyncOptions415	)416	cmd := &cobra.Command{417		Use:   "resync",418		Short: "Run config resync",419		Args:  cobra.NoArgs,420		RunE: func(cmd *cobra.Command, args []string) error {421			return runConfigResync(cli, opts)422		},423	}424	flags := cmd.Flags()425	flags.StringVarP(&opts.Format, "format", "f", "", "Format output")426	flags.BoolVar(&opts.Verbose, "verbose", false, "Run resync in verbose mode")427	flags.BoolVar(&opts.Retry, "retry", false, "Run resync with retries")428	return cmd429}430type ConfigResyncOptions struct {431	Format  string432	Verbose bool433	Retry   bool434}435// TODO: define default format with go template436const defaultFormatConfigResync = `json`437func runConfigResync(cli agentcli.Cli, opts ConfigResyncOptions) error {438	ctx, cancel := context.WithCancel(context.Background())439	defer cancel()440	rectxn, err := cli.Client().SchedulerResync(ctx, types.SchedulerResyncOptions{441		Retry:   opts.Retry,442		Verbose: opts.Verbose,443	})444	if err != nil {445		return err446	}447	format := opts.Format448	if len(format) == 0 {449		format = defaultFormatConfigResync450	}451	if err := formatAsTemplate(cli.Out(), format, rectxn); err != nil {452		return err453	}454	return nil455}456func newConfigHistoryCommand(cli agentcli.Cli) *cobra.Command {457	var (458		opts ConfigHistoryOptions459	)460	cmd := &cobra.Command{461		Use:   "history [REF]",462		Short: "Show config history",463		Long: `Show history of config changes and status updates464Prints a table of most important information about the history of changes to 465config and status updates that have occurred. You can filter the output by466specifying a reference to sequence number (txn ID).467Type can be one of:468 - config change  (NB - full resync)469 - status update  (SB)470 - config sync    (NB - upstream resync)471 - status sync    (NB - downstream resync)472 - retry #X for Y (retry of TX)473`,474		Example: `475# Show entire history476{{.CommandPath}} config history477# Show entire history with details478{{.CommandPath}} config history --details479# Show entire history in transaction log format480{{.CommandPath}} config history -f log481# Show entire history in classic log format482{{.CommandPath}} config history -f log483# Show history point with sequence number 3484{{.CommandPath}} config history 3485# Show history point with seq. number 3 in log format486{{.CommandPath}} config history -f log 3487`,488		Args: cobra.MaximumNArgs(1),489		RunE: func(cmd *cobra.Command, args []string) error {490			if len(args) > 0 {491				opts.TxnRef = args[0]492			}493			return runConfigHistory(cli, opts)494		},495	}496	flags := cmd.Flags()497	flags.StringVarP(&opts.Format, "format", "f", "", "Format output")498	flags.BoolVar(&opts.Details, "details", false, "Include details")499	return cmd500}501type ConfigHistoryOptions struct {502	Format  string503	Details bool504	TxnRef  string505}506func runConfigHistory(cli agentcli.Cli, opts ConfigHistoryOptions) (err error) {507	ctx, cancel := context.WithCancel(context.Background())508	defer cancel()509	ref := -1510	if opts.TxnRef != "" {511		ref, err = strconv.Atoi(opts.TxnRef)512		if err != nil {513			return fmt.Errorf("invalid reference: %q, use number > 0", opts.TxnRef)514		}515	}516	txns, err := cli.Client().SchedulerHistory(ctx, types.SchedulerHistoryOptions{517		SeqNum: ref,518	})519	if err != nil {520		return err521	}522	format := opts.Format523	if len(format) == 0 {524		printHistoryTable(cli.Out(), txns, opts.Details)525	} else if format == "log" {526		format = "{{.}}"527	}528	if err := formatAsTemplate(cli.Out(), format, txns); err != nil {529		return err530	}531	return nil532}533func printHistoryTable(out io.Writer, txns kvs.RecordedTxns, withDetails bool) {534	table := tablewriter.NewWriter(out)535	header := []string{536		"Seq", "Type", "Start", "Input", "Operations", "Result", "Summary",537	}538	if withDetails {539		header = append(header, "Details")540	}541	table.SetHeader(header)542	table.SetAutoWrapText(false)543	table.SetAutoFormatHeaders(true)544	table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)545	table.SetAlignment(tablewriter.ALIGN_LEFT)546	table.SetCenterSeparator("")547	table.SetColumnSeparator("")548	table.SetRowSeparator("")549	table.SetHeaderLine(false)550	table.SetBorder(false)551	table.SetTablePadding("\t")552	for _, txn := range txns {553		typ := getTxnType(txn)554		clr := getTxnColor(txn)555		age := shortHumanDuration(time.Since(txn.Start))556		var result string557		var resClr int...

Full Screen

Full Screen

logs.go

Source:logs.go Github

copy

Full Screen

1package logs2import (3	//"strings"4	"encoding/json"5	"fmt"6	"github.com/astaxie/beego"7	"github.com/astaxie/beego/logs"8)9// consoleLogs开发模式下日志10var consoleLogs *logs.BeeLogger11// fileLogs 生产环境下日志12var FileLogs *logs.BeeLogger13//运行方式14var runmode string15func InitLogger() (err error) {16	config := make(map[string]interface{})17	config["filename"] = beego.AppConfig.String("log_path")18	// map 转 json19	configStr, err := json.Marshal(config)20	if err != nil {21		fmt.Println("initLogger failed, marshal err:", err)22		return23	}24	// log 的配置25	beego.SetLogger(logs.AdapterFile, string(configStr))26	// log打印文件名和行数27	beego.SetLogFuncCall(true)28	fmt.Println(string(configStr))29	return30}31func InitLogs() {32	// consoleLogs = logs.NewLogger(1)33	// consoleLogs.SetLogger(logs.AdapterConsole)34	// consoleLogs.Async() //异步35	// fileLogs = logs.NewLogger(10000)36	// level := beego.AppConfig.String("logs::level")37	// fileLogs.SetLogger(logs.AdapterMultiFile, `{"filename":"logs/rms.log",38	// 	"separate":["emergency", "alert", "critical", "error", "warning", "notice", "info", "debug"],39	// 	"level":`+level+`,40	// 	"daily":true,41	// 	"maxdays":10}`)42	// fileLogs.Async() //异步43	// runmode = strings.TrimSpace(strings.ToLower(beego.AppConfig.String("runmode")))44	// if runmode == "" {45	// 	runmode = "dev"46	// }47	// 设置配置文件48	jsonConfig := `{49        "filename" : "/home/dragon/gocode/src/erpweb/log/test.log",50        "maxlines" : 1000,       51        "maxsize"  : 10240       52    }`53	FileLogs = logs.NewLogger(10000)54	FileLogs.SetLogger("file", jsonConfig) // 设置日志记录方式:本地文件记录55	FileLogs.SetLevel(logs.LevelError)     // 设置日志写入缓冲区的等级56	FileLogs.SetLevel(logs.LevelInfo)57	FileLogs.EnableFuncCallDepth(true) // 输出log时能显示输出文件名和行号(非必须)58	FileLogs.Async()59	Info("log start...")60	//log.Info("log start...")61}62func LogEmergency(v ...interface{}) {63	log("emergency", v)64}65func LogAlert(v ...interface{}) {66	log("alert", v)67}68func LogCritical(v ...interface{}) {69	log("critical", v)70}71func Error(v ...interface{}) {72	log("error", v)73}74func Warn(v ...interface{}) {75	log("warning", v)76}77func LogNotice(v ...interface{}) {78	log("notice", v)79}80func Info(v ...interface{}) {81	log("info", v)82}83func LogDebug(v ...interface{}) {84	log("debug", v)85}86func LogTrace(v ...interface{}) {87	log("trace", v)88}89//Log 输出日志90func log(level string, v ...interface{}) {91	format := "%s"92	if level == "" {93		level = "debug"94	}95	//if runmode == "dev" {96	switch level {97	case "emergency":98		FileLogs.Emergency(format, v)99	case "alert":100		FileLogs.Alert(format, v)101	case "critical":102		FileLogs.Critical(format, v)103	case "error":104		FileLogs.Error(format, v)105	case "warning":106		FileLogs.Warning(format, v)107	case "notice":108		FileLogs.Notice(format, v)109	case "info":110		FileLogs.Info(format, v)111	case "debug":112		FileLogs.Debug(format, v)113	case "trace":114		FileLogs.Trace(format, v)115	default:116		FileLogs.Debug(format, v)117	}118	//}119	// switch level {120	// case "emergency":121	// 	consoleLogs.Emergency(format, v)122	// case "alert":123	// 	consoleLogs.Alert(format, v)124	// case "critical":125	// 	consoleLogs.Critical(format, v)126	// case "error":127	// 	consoleLogs.Error(format, v)128	// case "warning":129	// 	consoleLogs.Warning(format, v)130	// case "notice":131	// 	consoleLogs.Notice(format, v)132	// case "info":133	// 	consoleLogs.Info(format, v)134	// case "debug":135	// 	consoleLogs.Debug(format, v)136	// case "trace":137	// 	consoleLogs.Trace(format, v)138	// default:139	// 	consoleLogs.Debug(format, v)140	// }141}...

Full Screen

Full Screen

format.go

Source:format.go Github

copy

Full Screen

...6	"bufio"7	"errors"8	"io"9)10// ErrFormat indicates that decoding encountered an unknown format.11var ErrFormat = errors.New("image: unknown format")12// A format holds an image format's name, magic header and how to decode it.13type format struct {14	name, magic  string15	decode       func(io.Reader) (Image, error)16	decodeConfig func(io.Reader) (Config, error)17}18// Formats is the list of registered formats.19var formats []format20// RegisterFormat registers an image format for use by Decode.21// Name is the name of the format, like "jpeg" or "png".22// Magic is the magic prefix that identifies the format's encoding. The magic23// string can contain "?" wildcards that each match any one byte.24// Decode is the function that decodes the encoded image.25// DecodeConfig is the function that decodes just its configuration.26func RegisterFormat(name, magic string, decode func(io.Reader) (Image, error), decodeConfig func(io.Reader) (Config, error)) {27	formats = append(formats, format{name, magic, decode, decodeConfig})28}29// A reader is an io.Reader that can also peek ahead.30type reader interface {31	io.Reader32	Peek(int) ([]byte, error)33}34// asReader converts an io.Reader to a reader.35func asReader(r io.Reader) reader {36	if rr, ok := r.(reader); ok {37		return rr38	}39	return bufio.NewReader(r)40}41// Match reports whether magic matches b. Magic may contain "?" wildcards.42func match(magic string, b []byte) bool {43	if len(magic) != len(b) {44		return false45	}46	for i, c := range b {47		if magic[i] != c && magic[i] != '?' {48			return false49		}50	}51	return true52}53// Sniff determines the format of r's data.54func sniff(r reader) format {55	for _, f := range formats {56		b, err := r.Peek(len(f.magic))57		if err == nil && match(f.magic, b) {58			return f59		}60	}61	return format{}62}63// Decode decodes an image that has been encoded in a registered format.64// The string returned is the format name used during format registration.65// Format registration is typically done by an init function in the codec-66// specific package.67func Decode(r io.Reader) (Image, string, error) {68	rr := asReader(r)69	f := sniff(rr)70	if f.decode == nil {71		return nil, "", ErrFormat72	}73	m, err := f.decode(rr)74	return m, f.name, err75}76// DecodeConfig decodes the color model and dimensions of an image that has77// been encoded in a registered format. The string returned is the format name78// used during format registration. Format registration is typically done by79// an init function in the codec-specific package.80func DecodeConfig(r io.Reader) (Config, string, error) {81	rr := asReader(r)82	f := sniff(rr)83	if f.decodeConfig == nil {84		return Config{}, "", ErrFormat85	}86	c, err := f.decodeConfig(rr)87	return c, f.name, err88}...

Full Screen

Full Screen

Format

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	viper.SetConfigName("config")4	viper.SetConfigType("json")5	viper.AddConfigPath(".")6	err := viper.ReadInConfig()7	if err != nil {8		panic(fmt.Errorf("Fatal error config file: %s \n", err))9	}10	fmt.Println("Before Set: ", viper.Get("database"))11	viper.Set("database", "mysql")12	fmt.Println("After Set: ", viper.Get("database"))13	viper.WriteConfig()14	fmt.Println("After Write: ", viper.Get("database"))15}16import (17func main() {18	viper.SetConfigName("config")19	viper.SetConfigType("json")20	viper.AddConfigPath(".")21	err := viper.ReadInConfig()22	if err != nil {23		panic(fmt.Errorf("Fatal error config file: %s \n", err))24	}25	fmt.Println("Before Bind: ", viper.Get("database"))26	viper.BindEnv("database", "DB_TYPE")27	fmt.Println("After Bind: ", viper.Get("database"))28}29import (30func main() {31	viper.SetConfigName("config")32	viper.SetConfigType("json")33	viper.AddConfigPath(".")34	err := viper.ReadInConfig()35	if err != nil {36		panic(fmt.Errorf("Fatal error config file: %s \n", err))37	}38	fmt.Println("Before Bind: ", viper.Get("database"))39	pflag.StringVarP(&dbType, "database", "d", "sqlite", "Database type")40	pflag.Parse()41	viper.BindPFlag("database", pflag.Lookup("database"))42	fmt.Println("After Bind: ", viper.Get("database"))43}

Full Screen

Full Screen

Format

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	viper.SetConfigName("config")4	viper.AddConfigPath(".")5	viper.SetConfigType("yaml")6	err := viper.ReadInConfig()7	if err != nil {8		fmt.Printf("Error while reading config file %s", err)9	}10	fmt.Println(viper.GetString("name"))11	fmt.Println(viper.GetString("age"))12	fmt.Println(viper.GetString("address"))13}

Full Screen

Full Screen

Format

Using AI Code Generation

copy

Full Screen

1import (2func main() {3		panic(fmt.Errorf("Fatal error config file: %s \n", err))4	}5	fmt.Println("Reading Config File")6	fmt.Println(viper.Get("name"))7	fmt.Println(viper.Get("age"))8	fmt.Println(viper.Get("address"))9	fmt.Println(viper.Get("skills"))10	fmt.Println(viper.Get("skills.0"))11	fmt.Println(viper.Get("skills.1"))12	fmt.Println(viper.Get("skills.2"))13	fmt.Println(viper.Get("skills.3"))14	fmt.Println(viper.Get("skills.4"))15	fmt.Println(viper.Get("skills.5"))16	fmt.Println(viper.Get("skills.6"))17	fmt.Println(viper.Get("skills.7"))18	fmt.Println(viper.Get("skills.8"))19	fmt.Println(viper.Get("skills.9"))20	fmt.Println(viper.Get("skills.10"))21	fmt.Println(viper.Get("skills.11"))22	fmt.Println(viper.Get("skills.12"))23	fmt.Println(viper.Get("skills.13"))24	fmt.Println(viper.Get("skills.14"))25	fmt.Println(viper.Get("skills.15"))26	fmt.Println(viper.Get("skills.16"))27	fmt.Println(viper.Get("skills.17"))28	fmt.Println(viper.Get("skills.18"))29	fmt.Println(viper.Get("skills.19"))30	fmt.Println(viper.Get("skills.20"))31	fmt.Println(viper.Get("skills.21"))32	fmt.Println(viper.Get("skills.22"))33	fmt.Println(viper.Get("skills.23"))34	fmt.Println(viper.Get("skills.24"))35	fmt.Println(viper.Get("skills.25"))36	fmt.Println(viper.Get("skills.26"))37	fmt.Println(viper.Get("skills.27"))38	fmt.Println(viper.Get("skills.28"))39	fmt.Println(viper.Get("skills.29"))40	fmt.Println(viper.Get("skills.30"))41	fmt.Println(viper.Get("skills.31"))42	fmt.Println(viper.Get("skills.32"))43	fmt.Println(viper.Get("skills.33"))44	fmt.Println(v

Full Screen

Full Screen

Format

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	t := time.Now()4	fmt.Println(t.Format("02/01/2006 15:04:05"))5	fmt.Println(t.Format("02-01-2006 15:04:05"))6	fmt.Println(t.Format("02/01/2006 03:04:05 PM"))7	fmt.Println(t.Format("02/01/2006"))8	fmt.Println(t.Format("15:04:05"))9	fmt.Println(t.Format("15:04:05 PM"))10	fmt.Println(t.Format("Jan 2, 2006"))11	fmt.Println(t.Format("2006-01-02"))12	fmt.Println(t.Format("2006-01-02 15:04:05"))13	fmt.Println(t.Format("2006-01-02 15:04:05.000"))14	fmt.Println(t.Format("2006-01-02 15:04:05.000000"))15	fmt.Println(t.Format("2006-01-02 15:04:05.000000000"))16	fmt.Println(t.Format("2006-01-02 15:04:05.000000000 -0700"))17	fmt.Println(t.Format("2006-01-02 15:04:05.000000000 -07:00"))18	fmt.Println(t.Format("2006-01-02 15:04:05.000000000 -07:00 MST"))19	fmt.Println(t.Format("2006-01-02 15:04:05.000000000 -07:00 MST 2006"))20	fmt.Println(t.Format("2006-01-02 15:04:05.000000000 -07:00 MST January"))21	fmt.Println(t.Format("2006-01-02 15:04:05.000000000 -07:00 MST January 2006"))22	fmt.Println(t.Format("2006-01-02 15:04:05.000000000 -07:00 MST January 2, 2006"))23	fmt.Println(t.Format("2006-01-02 15:04:05.000000000 -07:00 MST January 2, 2006 Monday"))24	fmt.Println(t.Format("2006-01-02 15:04:05.000000000 -07:00 MST January 2, 2006 Monday 15:04:05"))25	fmt.Println(t.Format

Full Screen

Full Screen

Format

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	viper.SetConfigName("config")4	viper.AddConfigPath(".")5	err := viper.ReadInConfig()6	if err != nil {7		fmt.Println("Error reading config file, %s", err)8	}9	fmt.Println("Reading value of key1 from config file")10	fmt.Println(viper.Get("key1"))11	fmt.Println("Reading value of key2 from config file")12	fmt.Println(viper.Get("key2"))13	fmt.Println("Reading value of key3 from config file")14	fmt.Println(viper.Get("key3"))15	fmt.Println("Reading value of key4 from config file")16	fmt.Println(viper.Get("key4"))17	fmt.Println("Reading value of key5 from config file")18	fmt.Println(viper.Get("key5"))19	fmt.Println("Reading value of key6 from config file")20	fmt.Println(viper.Get("key6"))21	fmt.Println("Reading value of key7 from config file")22	fmt.Println(viper.Get("key7"))23	fmt.Println("Reading value of key8 from config file")24	fmt.Println(viper.Get("key8"))25	fmt.Println("Reading value of key9 from config file")26	fmt.Println(viper.Get("key9"))27	fmt.Println("Reading value of key10 from config file")28	fmt.Println(viper.Get("key10"))29	fmt.Println("Reading value of key11 from config file")30	fmt.Println(viper.Get("key11"))31	fmt.Println("Reading value of key12 from config file")32	fmt.Println(viper.Get("key12"))33	fmt.Println("Reading value of key13 from config file")34	fmt.Println(viper.Get("key13"))35	fmt.Println("Reading value of key14 from config file")36	fmt.Println(viper.Get("key14"))37	fmt.Println("Reading value of key15 from config file")38	fmt.Println(viper.Get("key15"))39	fmt.Println("Reading value of key16 from config file")40	fmt.Println(viper.Get("key16"))41	fmt.Println("Reading value of key17 from config file")42	fmt.Println(viper.Get("key17"))43	fmt.Println("Reading value of key18 from config file")44	fmt.Println(viper.Get("key18"))45	fmt.Println("Reading value of key19 from config file")46	fmt.Println(viper.Get("key19"))47	fmt.Println("Reading value of key20 from config file")48	fmt.Println(viper.Get("key20"))49	fmt.Println("Reading value of

Full Screen

Full Screen

Format

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	app := cli.NewApp()4	app.Action = func(c *cli.Context) error {5		fmt.Println("config")6	}7	app.Run(os.Args)8}

Full Screen

Full Screen

Format

Using AI Code Generation

copy

Full Screen

1import (2func main() {3viper.SetConfigType("json")4viper.SetConfigName("config")5viper.AddConfigPath(".")6err := viper.ReadInConfig()7if err != nil {8fmt.Println("Error reading config file, %s", err)9}10fmt.Println(viper.Format())11}12import (13func main() {14viper.SetConfigType("json")15viper.SetConfigName("config")16viper.AddConfigPath(".")17err := viper.ReadInConfig()18if err != nil {19fmt.Println("Error reading config file, %s", err)20}21viper.Set("Name", "newConfig")22fmt.Println(viper.Get("Name"))23}24import (25func main() {26viper.SetConfigType("json")27viper.SetConfigName("config")28viper.AddConfigPath(".")29err := viper.ReadInConfig()30if err != nil {31fmt.Println("Error reading config file, %s", err)32}33viper.Set("Name", "newConfig")34fmt.Println(viper.Get("Name"))35}36import (37func main() {38viper.SetConfigType("json")39viper.SetConfigName("config")40viper.AddConfigPath(".")41err := viper.ReadInConfig()42if err != nil {43fmt.Println("Error reading config file, %s", err)44}45viper.SetDefault("Name", "newConfig")46fmt.Println(viper.Get("Name"))47}48import (

Full Screen

Full Screen

Format

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	viper.SetConfigName("config")4	viper.SetConfigType("json")5	viper.AddConfigPath(".")6	viper.AddConfigPath(".")7	err := viper.ReadInConfig()8	if err != nil {9		fmt.Println(err)10	}11	fmt.Println("Initial Config")12	fmt.Println(viper.AllSettings())13	viper.Set("name", "John")14	viper.Set("age", 22)15	viper.Set("address", "New York")16	viper.Set("skills", []string{"Go", "Python", "Java"})17	f, err := os.Create("config2.json")18	if err != nil {19		fmt.Println(err)20	}21	defer f.Close()22	viper.WriteConfig(f)23	viper.SetConfigType("json")24	viper.SetConfigFile("config2.json")25	err = viper.ReadInConfig()26	if err != nil {27		fmt.Println(err)28	}29	viper.Set("skills", strings.Join(viper.GetStringSlice("skills"), ", "))30	f, err = os.Create("config3.json")31	if err != nil {32		fmt.Println(err)33	}34	defer f.Close()35	viper.WriteConfig(f)36}

Full Screen

Full Screen

Format

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	c.Add("name", "Raj")4	c.Add("age", "23")5	c.Add("city", "Bangalore")6	fmt.Println(c.Format())7}8import (9type Config struct {10}11func (c *Config) Add(key string, value string) {12	if c.data == nil {13		c.data = make(map[string]string)14	}15}16func (c *Config) Format() string {17	for key, value := range c.data {18		buffer.WriteString(fmt.Sprintf("%s=%s", key, value))19		buffer.WriteString(strings.Repeat(" ", 10-len(key)))20		buffer.WriteString("\n")21	}22	return buffer.String()23}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful