• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang color.Red函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/fatih/color.Red函数的典型用法代码示例。如果您正苦于以下问题:Golang Red函数的具体用法?Golang Red怎么用?Golang Red使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Red函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: TestAnchorMerger

func TestAnchorMerger(t *testing.T) {
	color.NoColor = false

	in := []byte(`---
vars: &v
  env: qa
deploy:
  env: live`)
	expect := `{"deploy":{"env":"live"},"vars":{"env":"qa"}}`

	if err := ioutil.WriteFile("/tmp/test", in, 0644); err != nil {
		color.Red("Error file not create")
		t.Error("Error file not create")
		t.Fail()
	}

	defer os.Remove("/tmp/test")

	if g, err := LoadFile("/tmp/test"); err != nil {
		color.Red("%v\n", err)
		t.Error(err)
		t.Fail()
	} else {
		if g.String() == expect {
			color.Green("\n%s: OK\n", "FileLoad")
		} else {
			color.Red("%s != %s", g.String(), expect)
			t.Error(fmt.Errorf("%s != %s", g.String(), expect))
			t.Fail()
		}
	}
}
开发者ID:kulikov,项目名称:serve,代码行数:32,代码来源:loader_test.go


示例2: getClientCredentials

func getClientCredentials(c *cli.Context) []string {
	credentials := []string{c.GlobalString("client-id"), c.GlobalString("client-secret")}

	if credentials[0] == "" || credentials[1] == "" {
		color.Yellow("No client credentials given. Fallback to builtin default...")
		color.Yellow("Keep in mind that your document might be visible to other users.")
		color.Yellow("Your unique user-id is the only secret to protect your data.\n\n")

		superSecretSecret := []byte("V;4nJvuANmoywKNYk.yewNhqwmAQctc3BvByxeozQVpiK")

		// Decode HEX default credentials
		credentialsBytes, err := hex.DecodeString(defaultClientCredentials)
		if err != nil {
			color.Red("Error: client-id and client-secret missing and fallback decoding (step 1) failed: %s\n\n", err)
			cli.ShowCommandHelp(c, c.Command.FullName())
			os.Exit(1)
		}

		decodedCredentials := strings.Split(string(xorBytes(credentialsBytes, superSecretSecret)), ":")

		if len(decodedCredentials) < 2 {
			color.Red("Error: client-id and client-secret missing and fallback decoding (step 2) failed: %s\n\n", err)
			cli.ShowCommandHelp(c, c.Command.FullName())
			os.Exit(1)
		}
		credentials = decodedCredentials
	}

	return credentials
}
开发者ID:gini,项目名称:gapicmd,代码行数:30,代码来源:utils.go


示例3: Build

// Build listens watch events from Watcher and sends messages to Runner
// when new changes are built.
func (b *Builder) Build(p *Params) {
	go b.registerSignalHandler()
	go func() {
		b.watcher.update <- true
	}()

	for <-b.watcher.Wait() {
		fileName := p.createBinaryName()

		pkg := p.GetPackage()

		color.Cyan("Building %s...\n", pkg)

		// build package
		cmd, err := runCommand("go", "build", "-o", fileName, pkg)
		if err != nil {
			log.Fatalf("Could not run 'go build' command: %s", err)
			continue
		}

		if err := cmd.Wait(); err != nil {
			if err := interpretError(err); err != nil {
				color.Red("An error occurred while building: %s", err)
			} else {
				color.Red("A build error occurred. Please update your code...")
			}

			continue
		}

		// and start the new process
		b.runner.restart(fileName)
	}
}
开发者ID:rwuebker,项目名称:go-watcher,代码行数:36,代码来源:build.go


示例4: runAllProcessorTests

func runAllProcessorTests(t *testing.T, cases map[string]processorTestCase) {
	color.NoColor = false

	json := `{
		"var1": "var1",
		"var-var": "var-var",
		"var": {"var": "1"},
		"version": "{{ feature }}-{{ feature-suffix }}",
		"feature": "value-unknown",
		"feature-suffix": "{{ feature }}",
		"list": [1, 2, 3]
	}`

	tree, err := gabs.ParseJSON([]byte(json))
	if err != nil {
		color.Red("%v: failed!\n", err)
		t.Fail()
	}

	for name, test := range cases {
		if res, err := Template(test.in, tree); err == nil {
			if test.expect == res {
				color.Green("%v: Ok\n", name)
			} else {
				color.Red("%v: %v != %v: failed!\n", name, test.expect, res)
				t.Fail()
			}
		} else {
			color.Red("error %v\n: failed!", err)
			t.Fail()
		}
	}
}
开发者ID:kulikov,项目名称:serve,代码行数:33,代码来源:templater_test.go


示例5: Run

func (n *Notifier) Run(message string) {
	switch n.Name {
	case "slack":
		if slack_api == nil {
			color.Red("[!] Slack used as a notifier, but not configured with ENV vars.")
			return
		}
		err = slack_api.ChatPostMessage(slack_channel.Id, message, &slack.ChatPostMessageOpt{IconEmoji: ":fire:"})
		if err != nil {
			color.Red(fmt.Sprintf("[!] Error posting to Slack: %s", err))
		}
	case "hipchat":
		if hipchat_api == nil {
			color.Red("[!] HipChat used as a notifier, but not configured with ENV vars.")
			return
		}
		_, err = hipchat_api.Room.Notification(os.Getenv("HIPCHAT_ROOM_ID"), &hipchat.NotificationRequest{Message: "Testing", Color: "red"})
		if err != nil {
			color.Red(fmt.Sprintf("[!] Error posting to HipChat: %s", err))
		}
	case n.Name: // default
		color.Yellow(fmt.Sprintf("[>] Unknown notifier: %s", n.Name))
	}

}
开发者ID:joock,项目名称:influx-alert,代码行数:25,代码来源:notifiers.go


示例6: variables

func variables(v *vaulted.Vault) {
	exit := false

	for exit == false {
		printVariables(v)
		input := readMenu("\nEdit environment variables: [a,D,?,b]: ")
		switch input {
		case "a":
			variableKey := readValue("Name: ")
			variableValue := readValue("Value: ")
			if v.Vars == nil {
				v.Vars = make(map[string]string)
			}
			v.Vars[variableKey] = variableValue
		case "D":
			variable := readValue("Variable name: ")
			_, ok := v.Vars[variable]
			if ok {
				delete(v.Vars, variable)
			} else {
				color.Red("Variable '%s' not found", variable)
			}
		case "b":
			exit = true
		case "?", "help":
			variableMenu()
		default:
			color.Red("Command not recognized")
		}
	}
}
开发者ID:daveadams,项目名称:vaulted,代码行数:31,代码来源:edit.go


示例7: sshKeysMenu

func sshKeysMenu(v *vaulted.Vault) {
	exit := false

	for exit == false {
		printSSHKeys(v)
		input := readMenu("\nEdit ssh keys: [a,D,?,b]: ")
		switch input {
		case "a":
			addSSHKey(v)
		case "D":
			key := readValue("Key: ")
			_, ok := v.SSHKeys[key]
			if ok {
				delete(v.SSHKeys, key)
			} else {
				color.Red("Key '%s' not found", key)
			}
		case "b":
			exit = true
		case "?", "help":
			sshKeysHelp()
		default:
			color.Red("Command not recognized")
		}
	}
}
开发者ID:daveadams,项目名称:vaulted,代码行数:26,代码来源:edit.go


示例8: Output

func (r Documentation) Output(results <-chan []resource.TestResult) (hasFail bool) {
	testCount := 0
	var failed []resource.TestResult
	for resultGroup := range results {
		for _, testResult := range resultGroup {
			if testResult.Successful {
				fmt.Println(humanizeResult(testResult))
				testCount++
			} else {
				fmt.Println(humanizeResult(testResult))
				failed = append(failed, testResult)
				testCount++
			}
		}
		fmt.Println("")
	}

	fmt.Print("\n")
	if len(failed) > 0 {
		color.Red("Failures:")
		for _, testResult := range failed {
			fmt.Println(humanizeResult(testResult))
		}
		fmt.Print("\n")
	}

	if len(failed) > 0 {
		color.Red("Count: %d failed: %d\n", testCount, len(failed))
		return true
	}
	color.Green("Count: %d failed: %d\n", testCount, len(failed))
	return false
}
开发者ID:timstoop,项目名称:goss,代码行数:33,代码来源:documentation.go


示例9: getOpts

func getOpts(context *cli.Context) (string, string, string, string, string) {
	etcdURI := context.String("etcd-uri")
	redisURI := context.String("redis-uri")
	redisQueue := context.String("redis-queue")
	deployStateUri := context.String("deploy-state-uri")
	cluster := context.String("cluster")

	if etcdURI == "" || redisURI == "" || redisQueue == "" || deployStateUri == "" || cluster == "" {
		cli.ShowAppHelp(context)

		if etcdURI == "" {
			color.Red("  Missing required flag --etcd-uri or GOVERNATOR_ETCD_URI")
		}
		if redisURI == "" {
			color.Red("  Missing required flag --redis-uri or GOVERNATOR_REDIS_URI")
		}
		if redisQueue == "" {
			color.Red("  Missing required flag --redis-queue or GOVERNATOR_REDIS_QUEUE")
		}
		if deployStateUri == "" {
			color.Red("  Missing required flag --deploy-state-uri or DEPLOY_STATE_URI")
		}
		if cluster == "" {
			color.Red("  Missing required flag --cluster or CLUSTER")
		}
		os.Exit(1)
	}

	return etcdURI, redisURI, redisQueue, deployStateUri, cluster
}
开发者ID:octoblu,项目名称:governator,代码行数:30,代码来源:main.go


示例10: Validate

func Validate(c *cli.Context, startTime time.Time) {
	gossConfig := getGossConfig(c)
	sys := system.New(c)
	outputer := getOutputer(c)

	sleep := c.Duration("sleep")
	retryTimeout := c.Duration("retry-timeout")
	i := 1
	for {
		iStartTime := time.Now()
		out := validate(sys, gossConfig, c.Int("max-concurrent"))
		exitCode := outputer.Output(os.Stdout, out, iStartTime)
		if retryTimeout == 0 || exitCode == 0 {
			os.Exit(exitCode)
		}
		elapsed := time.Since(startTime)
		if elapsed+sleep > retryTimeout {
			color.Red("\nERROR: Timeout of %s reached before tests entered a passing state", retryTimeout)
			os.Exit(3)
		}
		color.Red("Retrying in %s (elapsed/timeout time: %.3fs/%s)\n\n\n", sleep, elapsed.Seconds(), retryTimeout)
		// Reset cache
		sys = system.New(c)
		time.Sleep(sleep)
		i++
		fmt.Printf("Attempt #%d:\n", i)
	}
}
开发者ID:aelsabbahy,项目名称:goss,代码行数:28,代码来源:validate.go


示例11: init

func init() {
	// Verifies the existance of an anirip folder in our temp directory
	_, err := os.Stat(tempDir)
	if err != nil {
		os.Mkdir(tempDir, 0777)
	}

	// Checks for the existance of our AdobeHDS script which we will get if we don't have it
	_, err = os.Stat(tempDir + string(os.PathSeparator) + "AdobeHDS.php")
	if err != nil {
		adobeHDSResp, err := anirip.GetHTTPResponse("GET", "https://raw.githubusercontent.com/K-S-V/Scripts/master/AdobeHDS.php", nil, nil, nil)
		if err != nil {
			color.Red("[anirip] There was an error retrieving AdobeHDS.php script from GitHub...")
			return
		}
		defer adobeHDSResp.Body.Close()
		adobeHDSBody, err := ioutil.ReadAll(adobeHDSResp.Body)
		if err != nil {
			color.Red("[anirip] There was an error reading the AdobeHDS.php body...")
			return
		}
		err = ioutil.WriteFile(tempDir+string(os.PathSeparator)+"AdobeHDS.php", adobeHDSBody, 0777)
		if err != nil {
			color.Red("[anirip] There was an error writing AdobeHDS.php to file...")
			return
		}
	}
}
开发者ID:sdwolfe32,项目名称:anirip,代码行数:28,代码来源:main.go


示例12: main

func main() {
	flag.Usage = usageExit
	flag.Parse()
	if *fversion {
		fmt.Printf("Stash: Version - %s\n", Version)
		return
	}

	log.SetFlags(0)
	log.SetPrefix("DEBUG: ")
	args := flag.Args()
	if len(args) < 1 {
		usageExit()
	}

	switch args[0] {
	case "help":
		help(args[1:])
		return
	case "destination", "dest":
		runCmd(subcmd.Destination, args[1:])
		return
	case "folder", "fold":
		runCmd(subcmd.Folder, args[1:])
		return
	case "daemon", "daem":
		runCmd(subcmd.Daemon, args[1:])
		return
	}

	color.Red("stash: unknown subcommand %q\n", args[0])
	color.Red("Run 'stash help' for usage.\n")
	os.Exit(2)
}
开发者ID:sparrc,项目名称:stash,代码行数:34,代码来源:main.go


示例13: Output

func (r Rspecish) Output(results <-chan []resource.TestResult, startTime time.Time) (exitCode int) {
	testCount := 0
	var failed []resource.TestResult
	for resultGroup := range results {
		for _, testResult := range resultGroup {
			if testResult.Successful {
				fmt.Printf(green("."))
			} else {
				fmt.Printf(red("F"))
				failed = append(failed, testResult)
			}
			testCount++
		}
	}

	fmt.Print("\n\n")
	if len(failed) > 0 {
		color.Red("Failures:")
		for _, testResult := range failed {
			fmt.Println(humanizeResult(testResult))
		}
		fmt.Print("\n")
	}

	fmt.Printf("Total Duration: %.3fs\n", time.Since(startTime).Seconds())
	if len(failed) > 0 {
		color.Red("Count: %d, Failed: %d\n", testCount, len(failed))
		return 1
	}
	color.Green("Count: %d, Failed: %d\n", testCount, len(failed))
	return 0
}
开发者ID:ryancox,项目名称:goss,代码行数:32,代码来源:rspecish.go


示例14: CopyFile

func CopyFile(conn *ssh.Client, FileName, DirectoryPath string) bool {
	defer conn.Close()
	if !strings.HasSuffix(DirectoryPath, "/") {
		DirectoryPath = DirectoryPath + "/"
	}
	con, err := sftp.NewClient(conn, sftp.MaxPacket(5e9))
	if err != nil {
		color.Red("%s传输文件新建会话错误: %s\n", conn.RemoteAddr(), err)
		return false
	}
	sFile, _ := os.Open(FileName)
	defer sFile.Close()
	dFile := DirectoryPath + FileName
	fmt.Printf("%s 目标路径:%s\n", conn.RemoteAddr(), dFile)
	File, err := con.OpenFile(dFile, os.O_CREATE|os.O_TRUNC|os.O_RDWR)
	if err != nil {
		color.Red("%s 创建文件%s错误: %s \n", conn.RemoteAddr(), dFile, err)
		return false
	}
	defer File.Close()
	for {
		buf := make([]byte, 1024)
		n, err := sFile.Read(buf)
		if err != nil {
			if err.Error() == "EOF" {
				break
			}
			return false
		}
		File.Write(buf[:n])
	}
	Result <- fmt.Sprintf("上传%s到%s成功.\n", FileName, conn.RemoteAddr())
	return true
}
开发者ID:czxichen,项目名称:Goprograme,代码行数:34,代码来源:sendfile.go


示例15: copyfile

func copyfile() {
	color.Yellow("开始执行文件发送:")
	info, err := os.Lstat(all_ssh.ArgsInfo.File)
	if err != nil || info.IsDir() {
		color.Blue("检查要发送的文件.")
		return
	}
	for _, v := range all_ssh.ServerList {
		go func() {
			client := all_ssh.Connection(v)
			if client != nil {
				all_ssh.CopyFile(client, all_ssh.ArgsInfo.File, all_ssh.ArgsInfo.Dir)
			}
		}()
	}
	var num int
	var Over chan os.Signal = make(chan os.Signal, 1)
	go signal.Notify(Over, os.Interrupt, os.Kill)
	go result(&num, Over)
	<-Over
	color.Yellow("一共有%d条错误.\n", len(all_ssh.ErrorList))
	for _, v := range all_ssh.ErrorList {
		color.Red(v)
	}
	color.Red("收到结果:%d条\n", num)
}
开发者ID:czxichen,项目名称:Goprograme,代码行数:26,代码来源:ssh_maste.go


示例16: printError

func (m *Manager) printError(body []byte) {
	e := Error{}
	err := json.Unmarshal(body, &e)
	if err != nil {
		color.Red(err.Error())
	}

	color.Red(e.Message)
}
开发者ID:supu-io,项目名称:supu,代码行数:9,代码来源:manager.go


示例17: uploadDocument

func uploadDocument(c *cli.Context) {
	filename := c.String("filename")
	doctype := c.String("doctype")
	userid := getUserIdentifier(c)

	if len(c.Args()) < 1 {
		cli.ShowCommandHelp(c, c.Command.FullName())
		return
	}

	if _, err := os.Stat(c.Args().First()); os.IsNotExist(err) {
		color.Red("\nError: cannot find %s\n\n", c.Args().First())
		cli.ShowCommandHelp(c, c.Command.FullName())
		return
	}

	bodyBuf, err := os.Open(c.Args().First())
	if err != nil {
		color.Red("\nError: failed to read %s\n\n", c.Args().First())
		cli.ShowCommandHelp(c, c.Command.FullName())
		return
	}

	api := getApiClient(c)

	doc, err := api.Upload(bodyBuf, giniapi.UploadOptions{
		FileName:       filename,
		DocType:        doctype,
		UserIdentifier: userid,
	})

	if err != nil {
		color.Red("\nError: %s\n\n", err)
		return
	}

	done <- true
	wg.Wait()

	renderResults(doc)

	if c.GlobalBool("curl") {
		curl := curlData{
			Headers: map[string]string{
				"Accept":            "application/vnd.gini.v1+json",
				"X-User-Identifier": userid,
			},
			Body:   fmt.Sprintf("--data-binary '@%s'", c.Args().First()),
			URL:    fmt.Sprintf("%s/documents", api.Endpoints.API),
			Method: "POST",
		}

		curl.render(c)
	}
}
开发者ID:gini,项目名称:gapicmd,代码行数:55,代码来源:gini.go


示例18: getProcessed

func getProcessed(c *cli.Context) {
	userid := getUserIdentifier(c)

	if len(c.Args()) != 2 {
		cli.ShowCommandHelp(c, c.Command.FullName())
		return
	}

	api := getApiClient(c)
	u := fmt.Sprintf("%s/documents/%s", api.Endpoints.API, c.Args().First())

	doc, err := api.Get(u, userid)

	if err != nil {
		color.Red("\nError: %s\n\n", err)
		return
	}

	body, err := doc.GetProcessed()

	if err != nil {
		color.Red("\nError: %s\n\n", err)
		return
	}

	err = ioutil.WriteFile(c.Args()[1], body, 0644)

	if err != nil {
		color.Red("\nError: %s\n\n", err)
		return
	}

	done <- true
	wg.Wait()

	renderResults(doc)

	if c.GlobalBool("curl") {
		curl := curlData{
			Headers: map[string]string{
				"Accept":            "application/vnd.gini.v1+json,application/octet-stream",
				"X-User-Identifier": userid,
			},
			Body:   "",
			URL:    doc.Links.Processed,
			Method: "GET",
		}

		curl.render(c)
	}
}
开发者ID:gini,项目名称:gapicmd,代码行数:51,代码来源:gini.go


示例19: getExtractions

func getExtractions(c *cli.Context) {
	incubator := c.Bool("incubator")
	userid := getUserIdentifier(c)

	if len(c.Args()) < 1 {
		cli.ShowCommandHelp(c, c.Command.FullName())
		return
	}

	api := getApiClient(c)
	u := fmt.Sprintf("%s/documents/%s", api.Endpoints.API, c.Args().First())

	doc, err := api.Get(u, userid)

	if err != nil {
		color.Red("\nError: %s\n\n", err)
		return
	}

	ext, err := doc.GetExtractions(incubator)
	if err != nil {
		color.Red("\nError: %s\n\n", err)
		return
	}

	done <- true
	wg.Wait()

	renderResults(ext)

	if c.GlobalBool("curl") {
		accept := "application/vnd.gini.v1+json"
		if incubator {
			accept = "application/vnd.gini.incubator+json"
		}

		curl := curlData{
			Headers: map[string]string{
				"Accept":            accept,
				"X-User-Identifier": userid,
			},
			Body:   "",
			URL:    doc.Links.Extractions,
			Method: "GET",
		}

		curl.render(c)
	}
}
开发者ID:gini,项目名称:gapicmd,代码行数:49,代码来源:gini.go


示例20: handleInteractiveMode

func handleInteractiveMode() {
	reader := bufio.NewReader(os.Stdin)
	for {
		red := color.New(color.FgCyan)
		red.Printf("%s %s %s => ", time.Now().Format("15:04:05"), *serverFlag, *executorFlag)

		line, err := reader.ReadString('\n')
		if err != nil {
			log.Fatal(color.RedString("ERROR reading string: %s", err.Error()))
		}
		line = strings.Trim(line, "\r\n")

		if strings.EqualFold(line, "exit") {
			color.Green("Exit command received. Good bye.")
			os.Exit(0)
		}

		exeAndArgs, err := parsecommand.Parse(line)
		if err != nil {
			color.Red("Cannot parse line '%s', error: %s", line, err.Error())
			continue
		}

		var exe string
		var args []string = []string{}

		exe = exeAndArgs[0]
		if len(exeAndArgs) > 1 {
			args = exeAndArgs[1:]
		}

		onFeedback := func(fb string) {
			fmt.Println(fb)
		}

		color.Green("Exe '%s' and args '%#v'", exe, args)
		color.Yellow("-------------------------------------")
		println()
		err = execute(false, onFeedback, *serverFlag, *executorFlag, *clientPemFlag, exe, args...)
		if err != nil {
			color.Red("Execute failed with error: %s", err.Error())
			continue
		}
		println()
		color.Yellow("-------------------------------------")
		println()
		println()
	}
}
开发者ID:golang-devops,项目名称:go-psexec,代码行数:49,代码来源:interactive_mode.go



注:本文中的github.com/fatih/color.Red函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang color.RedString函数代码示例发布时间:2022-05-23
下一篇:
Golang color.New函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap