当前位置: 首页>>代码示例>>Golang>>正文


Golang strconv.Quote函数代码示例

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


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

示例1: SaveStringsInPo

func SaveStringsInPo(printer PrinterInterface, options Options, stringInfos map[string]StringInfo, outputDirname string, fileName string) error {
	if len(stringInfos) != 0 {
		printer.Println("Creating and saving i18n strings to .po file:", fileName)
	}

	if !options.DryRunFlag && len(stringInfos) != 0 {
		err := CreateOutputDirsIfNeeded(outputDirname)
		if err != nil {
			printer.Println(err)
			return err
		}

		file, err := os.Create(filepath.Join(outputDirname, fileName[strings.LastIndex(fileName, string(os.PathSeparator))+1:len(fileName)]))
		defer file.Close()
		if err != nil {
			printer.Println(err)
			return err
		}

		for _, stringInfo := range stringInfos {
			file.Write([]byte("# filename: " + strings.Split(fileName, ".en.po")[0] +
				", offset: " + strconv.Itoa(stringInfo.Offset) +
				", line: " + strconv.Itoa(stringInfo.Line) +
				", column: " + strconv.Itoa(stringInfo.Column) + "\n"))
			file.Write([]byte("msgid " + strconv.Quote(stringInfo.Value) + "\n"))
			file.Write([]byte("msgstr " + strconv.Quote(stringInfo.Value) + "\n"))
			file.Write([]byte("\n"))
		}
	}
	return nil
}
开发者ID:krishicks,项目名称:i18n4go,代码行数:31,代码来源:common.go

示例2: OpenTSDBSingle

func (wr *TSWrite) OpenTSDBSingle() []byte {

	mJson := bytes.NewBuffer(make([]byte, 0))
	mJson.Write([]byte(`{`))
	mJson.Write([]byte(`"metric" : `))
	mJson.Write([]byte(strconv.Quote(wr.single.metric)))
	mJson.Write([]byte(`,`))
	mJson.Write([]byte(`"timestamp" : `))
	mJson.Write([]byte(strconv.FormatInt(wr.single.stamp/int64(time.Millisecond), 10)))
	mJson.Write([]byte(`,`))
	mJson.Write([]byte(`"value" : `))
	mJson.Write([]byte(strconv.FormatFloat(wr.single.value, 'f', -1, 64)))
	mJson.Write([]byte(`, `))
	mJson.Write([]byte(`"tags" : `))
	mJson.Write([]byte(`{`))

	var cnt int = 0
	for idx, value := range wr.single.tags {
		mJson.Write([]byte(strconv.Quote(idx) + " : "))
		mJson.Write([]byte(strconv.Quote(value)))
		if cnt < (len(wr.single.tags) - 1) {
			mJson.Write([]byte(`,`))
		}
		cnt++
	}

	mJson.Write([]byte(`}`))
	mJson.Write([]byte(`}`))

	return mJson.Bytes()

}
开发者ID:IMQS,项目名称:tsgen,代码行数:32,代码来源:rest.go

示例3: toJsonWebStatic

func (source *Translations) toJsonWebStatic(template *Translations) []byte {
	var buf bytes.Buffer
	var k, t string
	var order []string
	next := false

	hastemplate := template != nil && len((*template).Order) > 0

	if hastemplate {
		order = (*template).Order
	} else {
		order = (*source).Order
	}

	buf.WriteString("{\n")

	for i := 0; i < len(order); i++ {
		k = order[i]
		t = (*source).Data[k].Translation
		if len(t) == 0 && hastemplate {
			t = (*template).Data[k].Translation
		}

		if next {
			buf.WriteString(",\n")
		} else {
			next = true
		}
		buf.WriteString(fmt.Sprintf("%v%v: %v", indent, strconv.Quote(k), strconv.Quote(t)))
	}
	buf.WriteString("\n}\n")
	return buf.Bytes()
}
开发者ID:rodrigocorsi2,项目名称:mattermosti18n,代码行数:33,代码来源:mattermosti18n.go

示例4: ToPO

func (source *Translations) ToPO(target *Translations, template bool) []byte {
	var buf bytes.Buffer
	buf.WriteString((*source).Header)

	hastarget := target != nil && len((*target).Data) > 0

	var k, t string
	var po PO
	for i := 0; i < len((*source).Order); i = i + 1 {
		k = (*source).Order[i]
		po = (*source).Data[k]

		if hastarget {
			t = strconv.Quote((*target).Data[k].Translation) //translation in target language
		} else {
			t = strconv.Quote(po.Translation) //translation in source language (en)
		}

		buf.WriteString(fmt.Sprintln())
		buf.WriteString(fmt.Sprintf("#: %v\n", po.Localization))
		buf.WriteString(fmt.Sprintln("msgctxt", strconv.Quote(k)))
		buf.WriteString(fmt.Sprintln("msgid", strconv.Quote(po.Original)))

		if template {
			buf.WriteString(fmt.Sprintln("msgstr", `""`))
		} else {
			buf.WriteString(fmt.Sprintln("msgstr", t))
		}
	}

	return buf.Bytes()
}
开发者ID:treejames,项目名称:mattermosti18n,代码行数:32,代码来源:mattermosti18n.go

示例5: genStructFieldEncoder

func (g *Generator) genStructFieldEncoder(t reflect.Type, f reflect.StructField) error {
	jsonName := g.namer.GetJSONFieldName(t, f)
	tags := parseFieldTags(f)

	if tags.omit {
		return nil
	}
	if !tags.omitEmpty && !g.omitEmpty || tags.noOmitEmpty {
		fmt.Fprintln(g.out, "  if !first { out.RawByte(',') }")
		fmt.Fprintln(g.out, "  first = false")
		fmt.Fprintf(g.out, "  out.RawString(%q)\n", strconv.Quote(jsonName)+":")
		return g.genTypeEncoder(f.Type, "in."+f.Name, tags, 1)
	}

	fmt.Fprintln(g.out, "  if", g.notEmptyCheck(f.Type, "in."+f.Name), "{")
	fmt.Fprintln(g.out, "    if !first { out.RawByte(',') }")
	fmt.Fprintln(g.out, "    first = false")

	fmt.Fprintf(g.out, "    out.RawString(%q)\n", strconv.Quote(jsonName)+":")
	if err := g.genTypeEncoder(f.Type, "in."+f.Name, tags, 2); err != nil {
		return err
	}
	fmt.Fprintln(g.out, "  }")
	return nil
}
开发者ID:trdata,项目名称:easyjson,代码行数:25,代码来源:encoder.go

示例6: syncDir

func syncDir(bucket, keyPrefix, dir string) int {
	keyPrefix = strings.TrimPrefix(keyPrefix, "/")
	errCount := 0
	wg := &sync.WaitGroup{}
	filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		if info.IsDir() {
			return nil
		}
		rel, _ := filepath.Rel(dir, path)
		key := filepath.Join(keyPrefix, rel)
		wg.Add(1)
		go func() {
			log.Printf("Upload %v ...", strconv.Quote(key))
			if err := uploadFile(bucket, key, path); err != nil {
				errCount += 1
				log.Printf("Failed %v, %v", strconv.Quote(path), err)
			} else {
				log.Printf("Done %v", strconv.Quote(key))
			}
			wg.Done()
		}()
		return nil
	})
	wg.Wait()
	return errCount
}
开发者ID:gorelease,项目名称:qsync,代码行数:26,代码来源:main.go

示例7: PrepareForTemplate

// PrepareForTemplate uses the Columns slice to transform the rows so that correct Go code can be printed.
// int/Float values won't be touched. Bools or IntBools will be converted to true/false. Strings will be quoted.
// And if there is an entry in the AttributeModelMap then the Go code from the map will be used.
// Returns a slice containing all the import paths. Import paths which are equal to pkg will be filtered out.
func PrepareForTemplate(cols Columns, rows []StringEntities, amm AttributeModelDefMap, targetPkg string) []string {
	ip := make([]string, 0, 10) // import_path container
	for _, row := range rows {
		for colName, colValue := range row {
			var c = cols.GetByName(colName)

			if false == c.Field.Valid {
				continue
			}

			goType, hasModel := amm[colValue]
			_, isAllowedInterfaceChange := EavAttributeColumnNameToInterface[colName]
			switch {
			case hasModel:
				row[colName] = "nil"
				if goType.GoFunc != "" {
					row[colName] = goType.Func()
					if validImportPath(goType, ip, targetPkg) {
						ip = append(ip, goType.Import())
					}
				}
				break
			case isAllowedInterfaceChange:
				// if there is no defined model but column is (backend|frontend|data|source)_model then nil it
				row[colName] = "nil"
				break
			case c.IsBool():
				row[colName] = "false"
				if colValue == "1" {
					row[colName] = "true"
				}
				break
			case c.IsInt():
				if colValue == "" {
					row[colName] = "0"
				}
				break
			case c.IsString():
				row[colName] = strconv.Quote(colValue)
				break
			case c.IsFloat():
				if colValue == "" {
					row[colName] = "0.0"
				}
				break
			case c.IsDate():
				if colValue == "" {
					row[colName] = "nil"
				} else {
					row[colName] = "time.Parse(`2006-01-02 15:04:05`," + strconv.Quote(colValue) + ")" // @todo timezone
				}
				break
			default:
				panic(fmt.Sprintf("\nERROR cannot detect SQL type: %s -> %s\n%#v\n", colName, colValue, c))
			}

		}
	}
	return ip
}
开发者ID:joao-parana,项目名称:csfw,代码行数:64,代码来源:database.go

示例8: getMessage

func (e *goof) getMessage(includeFields bool) string {

	if !includeFields {
		return e.msg
	}

	buf := &bytes.Buffer{}
	fmt.Fprintf(buf, "msg=%q", e.msg)

	for k, v := range e.data {
		sv := fmt.Sprintf("%v", v)
		if m := dublQuoteRX.FindStringSubmatch(sv); len(m) > 0 {
			sv = m[1]
		} else if m := snglQuoteRX.FindStringSubmatch(sv); len(m) > 0 {
			sv = m[1]
		} else if m := backQuoteRX.FindStringSubmatch(sv); len(m) > 0 {
			sv = m[1]
		}
		if containsWS.MatchString(k) {
			k = strconv.Quote(k)
		}
		if containsWS.MatchString(sv) {
			sv = strconv.Quote(sv)
		}
		fmt.Fprintf(buf, " %s=%s", k, sv)
	}

	return buf.String()
}
开发者ID:akutz,项目名称:goof,代码行数:29,代码来源:goof.go

示例9: RewriteImports

// RewriteImports rewrites imports in the passed AST (in-place).
// It returns bool changed set to true if any changes were made
// and non-nil err on error
func RewriteImports(f *ast.File, prefix string, remove bool) (changed bool, err error) {
	for _, impNode := range f.Imports {
		imp, err := strconv.Unquote(impNode.Path.Value)
		if err != nil {
			log.Printf("Error unquoting import value %v - %s\n", impNode.Path.Value, err)
			return false, err
		}
		// skip standard library imports and relative references
		if !strings.Contains(imp, ".") || strings.HasPrefix(imp, ".") {
			continue
		}
		if remove {
			if strings.HasPrefix(imp, prefix) {
				changed = true
				impNode.Path.Value = strconv.Quote(imp[len(prefix):])
			}
		} else {
			// if import does not start with the prefix already, add it
			if !strings.HasPrefix(imp, prefix) {
				changed = true
				impNode.Path.Value = strconv.Quote(prefix + imp)
			}
		}
	}
	return
}
开发者ID:postfix,项目名称:prewrite,代码行数:29,代码来源:rewrite.go

示例10: PopulateBuffer

// Renders the coordinates of the ElasticSearch document as JSON.
func (e *ElasticSearchCoordinates) PopulateBuffer(m *message.Message, buf *bytes.Buffer) {
	buf.WriteString(`{"index":{"_index":`)

	var (
		err         error
		interpIndex string
		interpType  string
		interpId    string
	)

	interpIndex, err = interpolateFlag(e, m, e.Index)

	buf.WriteString(strconv.Quote(interpIndex))
	buf.WriteString(`,"_type":`)

	interpType, err = interpolateFlag(e, m, e.Type)
	buf.WriteString(strconv.Quote(interpType))

	//Interpolate the Id flag
	interpId, err = interpolateFlag(e, m, e.Id)

	//Check that Id successfully interpolated. If not then do not specify id
	//at all and default to auto-generated one.
	if len(e.Id) > 0 && err == nil {
		buf.WriteString(`,"_id":`)
		buf.WriteString(strconv.Quote(interpId))
	}
	buf.WriteString(`}}`)
}
开发者ID:RogerBai,项目名称:heka,代码行数:30,代码来源:coordinates.go

示例11: outputCsv

func outputCsv(writer io.Writer, dependency *Dependency) {
	for _, module := range dependency.modules {
		for _, to := range keys(dependency.relation[module]) {
			fmt.Fprintf(writer, "%s,%s\n", strconv.Quote(module), strconv.Quote(to))
		}
	}
}
开发者ID:kajisha,项目名称:rexdep,代码行数:7,代码来源:output.go

示例12: run

/* run parses a line and runs the appropriate command.  Source should be
something that identifies the caller, like an IP address.  Ding should be a
"\a" for a bell every command, or the empty string. */
func run(line, source, ding string) error {
	commandsL.Lock()
	defer commandsL.Unlock()
	/* Make sure we actually have a command */
	if 0 == len(line) {
		return nil
	}
	/* Split into fields */
	a := strings.Fields(line)
	if 0 == len(a) {
		return nil
	}
	/* Get the function to call */
	f, ok := commands[a[0]]
	if !ok {
		fmt.Printf("Nice Try!\n")
		log.Printf(
			"%v!: Unable to find command %v",
			source,
			strconv.Quote(line),
		)
		return nil
	}
	/* Comms channel */
	pr, pw := io.Pipe()
	defer pr.Close()
	defer pw.Close()
	go io.Copy(os.Stdout, pr)

	/* Start the command */
	log.Printf("%v%v: %v", ding, source, strconv.Quote(line))

	f(a[0], a[1:], pw)
	return nil
}
开发者ID:magisterquis,项目名称:ntsh,代码行数:38,代码来源:command.go

示例13: checkWarningExpectation

func checkWarningExpectation(prog *ssa.Program, e *expectation, warnings []pointer.Warning) bool {
	// TODO(adonovan): check the position part of the warning too?
	re, err := regexp.Compile(e.args[0])
	if err != nil {
		e.errorf("invalid regular expression in @warning expectation: %s", err.Error())
		return false
	}

	if len(warnings) == 0 {
		e.errorf("@warning %s expectation, but no warnings", strconv.Quote(e.args[0]))
		return false
	}

	for _, w := range warnings {
		if re.MatchString(w.Message) {
			return true
		}
	}

	e.errorf("@warning %s expectation not satised; found these warnings though:", strconv.Quote(e.args[0]))
	for _, w := range warnings {
		fmt.Printf("%s: warning: %s\n", prog.Fset.Position(w.Pos), w.Message)
	}
	return false
}
开发者ID:glycerine,项目名称:llgo,代码行数:25,代码来源:pointer_test.go

示例14: printExportFunction

func printExportFunction(ctx context.Context, env *envctx.Env, g *builder.Builder, export *sysctx.SysExportInfo) error {
	g.Println("func ", system.GoName(export.Name), "() *", g.SprintRef(export.TypePackage, system.GoName(export.TypeName)), " {")
	{
		g.Print("ctx := ")
		g.PrintFunctionCall("kego.io/system", "NewContext",
			g.SprintFunctionCall("context", "Background"),
			strconv.Quote(env.Path),
			fmt.Sprintf("%#v", env.Aliases),
		)
		g.Println()

		g.Println("o := new(", g.SprintRef(export.TypePackage, system.GoName(export.TypeName)), ")")

		g.Print("err := ")
		g.PrintMethodCall("o", "Unpack",
			"ctx",
			g.SprintFunctionCall("kego.io/system", "MustPackString", strconv.Quote(string(export.JsonContents))),
			"false",
		)
		g.Println()
		g.Println("if err != nil {")
		{
			g.Println("panic(err.Error())")
		}
		g.Println("}")
		g.Println("return o")
	}
	g.Println("}")
	return nil
}
开发者ID:kego,项目名称:ke,代码行数:30,代码来源:structs.go

示例15: Parse

func (k *KeywordRule) Parse(p *Parser) Result {
	p.Enter("KeywordRule(%s)", k.Value)
	defer p.Exit()
	p.PushTransaction()

	tok := p.Next()
	if tok.Type != TokenKeyword {
		p.Discard()

		return Result{Type: NoMatch,
			Message: Message(k.RuleName(), tok.Position, "Expected keyword got %s (at %s)",
				tok.Type, tok.Position)}
	}

	if tok.Value != k.Value {
		p.Discard()

		return Result{Type: NoMatch,
			Message: Message(k.RuleName(), tok.Position, "Expected %s, got %s (at %s)",
				strconv.Quote(k.Value), strconv.Quote(tok.Value), tok.Position)}
	}

	p.Commit()
	return Result{Type: Match, Value: tok}
}
开发者ID:kiljacken,项目名称:jai,代码行数:25,代码来源:parser.go


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