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


Golang strconv.Unquote函数代码示例

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


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

示例1: toBasicLitString

func toBasicLitString(n ast.Node) *ast.BasicLit {
	switch node := n.(type) {
	case *ast.BasicLit:
		if node.Kind == token.STRING {
			return node
		}
	case *ast.BinaryExpr:
		if node.Op != token.ADD {
			return nil
		}
		X := toBasicLitString(node.X)
		Y := toBasicLitString(node.Y)
		if X == nil || Y == nil {
			return nil
		}
		x, _ := strconv.Unquote(X.Value)
		y, _ := strconv.Unquote(Y.Value)
		return &ast.BasicLit{
			ValuePos: node.Pos(),
			Kind:     token.STRING,
			Value:    strconv.Quote(x + y),
		}
	case *ast.ParenExpr:
		x := toBasicLitString(node.X)
		if x == nil {
			return nil
		}
		x.ValuePos = node.Pos()
		return x
	}
	return nil
}
开发者ID:LukeShu,项目名称:periwinkle,代码行数:32,代码来源:xgettext.go

示例2: main

func main() {
	var mode string
	flag.StringVar(&mode, "mode", "", "package_imports|package_imports_tests")
	flag.Parse()
	switch mode {
	case "package_imports":
		for fileNode := range parseArgs() {
			fmt.Printf("package %s\n", fileNode.Name.Name)
			for spec := range extractImports(fileNode) {
				importPath, _ := strconv.Unquote(string(spec.Path.Value))
				fmt.Printf("import %s\n", importPath)
			}
		}
	case "package_imports_tests":
		for fileNode := range parseArgs() {
			fmt.Printf("package %s\n", fileNode.Name.Name)
			for spec := range extractImports(fileNode) {
				importPath, _ := strconv.Unquote(string(spec.Path.Value))
				fmt.Printf("import %s\n", importPath)
			}
			for decl := range extractTests(fileNode) {
				fmt.Printf("%s.%s\n", fileNode.Name.Name, decl.Name.Name)
			}
		}
	default:
		flag.Usage()
		os.Exit(1)
	}
}
开发者ID:alberts,项目名称:goscons,代码行数:29,代码来源:helper.go

示例3: parseDefinition

// parseDefinition parses a {{define}} ... {{end}} template definition and
// returns a defineNode. The "define" keyword has already been scanned.
//
//	{{define stringValue}} itemList {{end}}
//	{{define stringValue stringValue}} itemList {{end}}
func (p *parser) parseDefinition(pos Pos) *DefineNode {
	const context = "define clause"
	defer p.popVars(1)
	line := p.lex.lineNumber()
	var name, parent string
	token := p.nextNonSpace()
	switch token.typ {
	case itemString, itemRawString:
		s, err := strconv.Unquote(token.val)
		if err != nil {
			p.error(err)
		}
		name = s
	default:
		p.unexpected(token, context)
	}
	token = p.nextNonSpace()
	switch token.typ {
	case itemString, itemRawString:
		s, err := strconv.Unquote(token.val)
		if err != nil {
			p.error(err)
		}
		parent = s
		p.expect(itemRightDelim, context)
	case itemRightDelim:
	default:
		p.unexpected(token, context)
	}
	list, end := p.itemList()
	if end.Type() != nodeEnd {
		p.errorf("unexpected %s in %s", end, context)
	}
	return newDefine(pos, line, name, parent, list, p.text)
}
开发者ID:gorilla,项目名称:template,代码行数:40,代码来源:parse.go

示例4: bind

func (bnd *bndBool) bind(value bool, position int, c StmtCfg, stmt *Stmt) (err error) {
	//Log.Infof("%s.bind(%t, %d)", bnd, value, position)
	bnd.stmt = stmt
	var str string
	if value {
		str, err = strconv.Unquote(strconv.QuoteRune(c.TrueRune))
	} else {
		str, err = strconv.Unquote(strconv.QuoteRune(c.FalseRune))
	}
	if err != nil {
		return err
	}
	bnd.cString = C.CString(str)
	r := C.OCIBINDBYPOS(
		bnd.stmt.ocistmt,            //OCIStmt      *stmtp,
		(**C.OCIBind)(&bnd.ocibnd),  //OCIBind      **bindpp,
		bnd.stmt.ses.srv.env.ocierr, //OCIError     *errhp,
		C.ub4(position),             //ub4          position,
		unsafe.Pointer(bnd.cString), //void         *valuep,
		C.LENGTH_TYPE(1),            //sb8          value_sz,
		C.SQLT_AFC,                  //ub2          dty,
		nil,                         //void         *indp,
		nil,                         //ub2          *alenp,
		nil,                         //ub2          *rcodep,
		0,                           //ub4          maxarr_len,
		nil,                         //ub4          *curelep,
		C.OCI_DEFAULT)               //ub4          mode );
	if r == C.OCI_ERROR {
		return bnd.stmt.ses.srv.env.ociError()
	}
	return nil
}
开发者ID:optimuse,项目名称:ora,代码行数:32,代码来源:bndBool.go

示例5: init

func init() {
	flag.StringVar(&driver, "driver", "", "Sets the driver")
	flag.StringVar(&source, "source", "", "Sets the source")
	flag.StringVar(&schemaPath, "schema", "db/schema.go", "Sets the schema path")
	flag.IntVar(&steps, "steps", 0, "Sets the steps")
	flag.Parse()

	if driver == "" {
		panic("driver not set")
	}
	if source == "" {
		panic("source not set")
	}

	// Unquote
	d, err := strconv.Unquote(driver)
	if err != nil {
		panic(err)
	}
	driver = d

	s, err := strconv.Unquote(source)
	if err != nil {
		panic(err)
	}
	source = s

	sp, err := strconv.Unquote(schemaPath)
	if err != nil {
		panic(err)
	}
	schemaPath = sp
}
开发者ID:kspector,项目名称:hood,代码行数:33,代码来源:_runner.go

示例6: TestKubeVersion

func TestKubeVersion(t *testing.T) {
	Convey("Subject: Version Checking", t, func() {
		kversion, err := exec.Command("kubectl", "version").Output()
		Convey("kubectl version returns no error", func() {
			So(err, ShouldBeNil)
		})
		versions := bytes.Split(kversion, []byte("\n"))
		cver := string(versions[0])
		cver = cver[strings.IndexRune(cver, '{')+1:]
		cver = strings.TrimRight(cver, "}")
		sver := string(versions[1])
		sver = sver[strings.IndexRune(sver, '{')+1:]
		sver = strings.TrimRight(sver, "}")
		Convey("Subject: Client and Server version should be equal", func() {
			So(cver, ShouldEqual, sver)
		})
		kver := strings.Split(cver, ",")
		vmap := make(map[string]string)
		for _, item := range kver {
			entry := strings.Split(strings.TrimSpace(item), ":")
			vmap[entry[0]] = entry[1]
		}

		rversion, err := exec.Command("rpm", "-q", "kubernetes").Output()
		Convey("rpm -q kubernetes returns no error", func() {
			So(err, ShouldBeNil)
		})
		srver := string(rversion)
		rgit := strings.Split(srver, "-")[1]
		rver := strings.FieldsFunc(srver, func(r rune) bool {
			return r == '-' || r == '.'
		})
		rmajor := rver[1]
		rminor := rver[2]
		rcommit := rver[7][3:]
		vmajor, err := strconv.Unquote(vmap["Major"])
		Convey("unquote major return no error", func() {
			So(err, ShouldBeNil)
		})
		Convey("version major should match", func() {
			So(vmajor, ShouldEqual, rmajor)
		})
		vminor, err := strconv.Unquote(vmap["Minor"])
		Convey("unquote minor return no error", func() {
			So(err, ShouldBeNil)
		})
		Convey("version minor should match", func() {
			So(vminor, ShouldEqual, rminor)
		})
		Convey("rpm git version should be within kubectl git version", func() {
			So(vmap["GitVersion"], ShouldContainSubstring, rgit)
		})
		Convey("rpm git commit should be within kubectl git commit", func() {
			So(vmap["GitCommit"], ShouldContainSubstring, rcommit)
		})
	})
}
开发者ID:gouyang,项目名称:kubernetes-testing,代码行数:57,代码来源:version_test.go

示例7: NewSubStringExpr

func NewSubStringExpr(a, b Attrib) (*SubStringExpr, error) {
	astr, err := strconv.Unquote(string(a.(*token.Token).Lit))
	if err != nil {
		return nil, err
	}
	bstr, err := strconv.Unquote(string(b.(*token.Token).Lit))
	if err != nil {
		return nil, err
	}
	return &SubStringExpr{astr, bstr}, nil
}
开发者ID:seerdomin,项目名称:gocc,代码行数:11,代码来源:ast.go

示例8: Run

func (cmd *ntuple_create) Run() gribble.Value {
	id := cmd.Id
	title, err := strconv.Unquote(cmd.Title)
	if err != nil {
		return err
	}
	//nvars := cmd.Nvars.(int)
	vars, err := strconv.Unquote(cmd.Vars)
	ntvars := strings.Split(vars, ",")
	return cmd.mgr.Create(id, title, ntvars)
}
开发者ID:sbinet,项目名称:paw-go,代码行数:11,代码来源:cmds.go

示例9: checkCanonicalFieldTag

// checkCanonicalFieldTag checks a single struct field tag.
func checkCanonicalFieldTag(f *File, field *ast.Field, seen *map[[2]string]token.Pos) {
	if field.Tag == nil {
		return
	}

	tag, err := strconv.Unquote(field.Tag.Value)
	if err != nil {
		f.Badf(field.Pos(), "unable to read struct tag %s", field.Tag.Value)
		return
	}

	if err := validateStructTag(tag); err != nil {
		raw, _ := strconv.Unquote(field.Tag.Value) // field.Tag.Value is known to be a quoted string
		f.Badf(field.Pos(), "struct field tag %#q not compatible with reflect.StructTag.Get: %s", raw, err)
	}

	for _, key := range checkTagDups {
		val := reflect.StructTag(tag).Get(key)
		if val == "" || val == "-" || val[0] == ',' {
			continue
		}
		if i := strings.Index(val, ","); i >= 0 {
			val = val[:i]
		}
		if *seen == nil {
			*seen = map[[2]string]token.Pos{}
		}
		if pos, ok := (*seen)[[2]string{key, val}]; ok {
			f.Badf(field.Pos(), "struct field %s repeats %s tag %q also at %s", field.Names[0].Name, key, val, f.loc(pos))
		} else {
			(*seen)[[2]string{key, val}] = field.Pos()
		}
	}

	// Check for use of json or xml tags with unexported fields.

	// Embedded struct. Nothing to do for now, but that
	// may change, depending on what happens with issue 7363.
	if len(field.Names) == 0 {
		return
	}

	if field.Names[0].IsExported() {
		return
	}

	for _, enc := range [...]string{"json", "xml"} {
		if reflect.StructTag(tag).Get(enc) != "" {
			f.Badf(field.Pos(), "struct field %s has %s tag but is not exported", field.Names[0].Name, enc)
			return
		}
	}
}
开发者ID:achanda,项目名称:go,代码行数:54,代码来源:structtag.go

示例10: resolveExtension

func resolveExtension(extension string) (resolved string) {
	resp, err := http.Get(caddyRegistry)
	if err != nil {
		return
	}

	defer resp.Body.Close()
	data, err := ioutil.ReadAll(resp.Body)

	f, err := parser.ParseFile(token.NewFileSet(), "", data, 0)
	node, ok := f.Scope.Lookup("Registry").Decl.(ast.Node)
	if !ok {
		return
	}

	c := node.(*ast.ValueSpec).Values[0].(*ast.CompositeLit)
	for _, m := range c.Elts {
		var directive *ast.BasicLit
		var directiveRepo *ast.BasicLit
		token := m.(*ast.CompositeLit).Elts

		if v, ok := token[0].(*ast.BasicLit); ok {
			directive = v
		} else {
			return
		}

		name, err := strconv.Unquote(directive.Value)
		if err != nil {
			return
		}

		if v, ok := token[1].(*ast.BasicLit); ok {
			directiveRepo = v
		} else {
			return
		}

		repo, err := strconv.Unquote(directiveRepo.Value)
		if err != nil {
			return
		}

		if name == extension {
			if len(repo) > 0 {
				resolved = repo
			}
			return
		}
	}

	return
}
开发者ID:klauern,项目名称:caddyext,代码行数:53,代码来源:install.go

示例11: basicLit

func (p *noder) basicLit(lit *syntax.BasicLit) Val {
	// TODO: Don't try to convert if we had syntax errors (conversions may fail).
	//       Use dummy values so we can continue to compile. Eventually, use a
	//       form of "unknown" literals that are ignored during type-checking so
	//       we can continue type-checking w/o spurious follow-up errors.
	switch s := lit.Value; lit.Kind {
	case syntax.IntLit:
		x := new(Mpint)
		x.SetString(s)
		return Val{U: x}

	case syntax.FloatLit:
		x := newMpflt()
		x.SetString(s)
		return Val{U: x}

	case syntax.ImagLit:
		x := new(Mpcplx)
		x.Imag.SetString(strings.TrimSuffix(s, "i"))
		return Val{U: x}

	case syntax.RuneLit:
		var r rune
		if u, err := strconv.Unquote(s); err == nil && len(u) > 0 {
			// Package syntax already reported any errors.
			// Check for them again though because 0 is a
			// better fallback value for invalid rune
			// literals than 0xFFFD.
			if len(u) == 1 {
				r = rune(u[0])
			} else {
				r, _ = utf8.DecodeRuneInString(u)
			}
		}
		x := new(Mpint)
		x.SetInt64(int64(r))
		x.Rune = true
		return Val{U: x}

	case syntax.StringLit:
		if len(s) > 0 && s[0] == '`' {
			// strip carriage returns from raw string
			s = strings.Replace(s, "\r", "", -1)
		}
		// Ignore errors because package syntax already reported them.
		u, _ := strconv.Unquote(s)
		return Val{U: u}

	default:
		panic("unhandled BasicLit kind")
	}
}
开发者ID:hurkgu,项目名称:go,代码行数:52,代码来源:noder.go

示例12: main

func main() {
	interval, _ := strconv.ParseInt(os.Getenv("LABELGUN_INTERVAL"), 10, 64)
	kube_master = os.Getenv("KUBE_MASTER")
	for {
		// Get Kube Node name
		n, _ := sh.Command("kubectl", "-s", kube_master, "describe", "pod", os.Getenv("HOSTNAME")).Command("grep", "Node").Command("awk", "{print $2}").Command("sed", "[email protected]/.*@@").Output()
		node = string(n)
		node = strings.TrimSpace(node)
		fmt.Println(node)

		// Get instance id
		instance_id, _ := sh.Command("curl", "-s", "http://169.254.169.254/latest/meta-data/instance-id").Output()
		fmt.Println(string(instance_id))

		// Get AWS instance metadata
		params := &ec2.DescribeInstancesInput{
			InstanceIds: []*string{
				aws.String(string(instance_id)),
			},
		}
		resp, err := svc.DescribeInstances(params)

		if err != nil {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
			return
		}

		// Pretty-print the response data.
		//fmt.Println(resp.Reservations[0].Instances[0].InstanceType)
		meta = resp.Reservations[0].Instances[0]

		// Apply Availability Zone
		availabilityZone, _ := strconv.Unquote(string(awsutil.Prettify(meta.Placement.AvailabilityZone)))
		label("AvailabilityZone=" + availabilityZone)

		// Apply Instance Type
		instanceType, _ := strconv.Unquote(string(awsutil.Prettify(meta.InstanceType)))
		label("InstanceType=" + instanceType)

		// Apply EC2 Tags
		tags := meta.Tags
		for _, tag := range tags {
			label(*tag.Key + "=" + *tag.Value)
		}
		// Sleep until interval
		fmt.Println("Sleeping for " + os.Getenv("LABELGUN_INTERVAL") + " seconds")
		time.Sleep(time.Duration(interval) * time.Second)
	}

}
开发者ID:Vungle,项目名称:labelgun,代码行数:52,代码来源:labelgun.go

示例13: FindEnv

// FindEnv returns map of environment variables.
// Key of map is key of environment variable, Value of map is value of
// environment variable.
func FindEnv(basedir string) (map[string]string, error) {
	if basedir == "" {
		pwd, err := os.Getwd()
		if err != nil {
			return nil, err
		}
		basedir = pwd
	}
	env := make(map[string]string)
	if err := filepath.Walk(basedir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		switch info.Name()[0] {
		case '.', '_':
			if info.IsDir() {
				return filepath.SkipDir
			}
			return nil
		}
		if info.IsDir() {
			return nil
		}
		if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
			return nil
		}
		body, err := ioutil.ReadFile(path)
		if err != nil {
			return err
		}
		matches := settingEnvRegexp.FindAllStringSubmatch(string(body), -1)
		if matches == nil {
			return nil
		}
		for _, m := range matches {
			key, err := strconv.Unquote(m[1])
			if err != nil {
				continue
			}
			value, err := strconv.Unquote(m[2])
			if err != nil {
				value = "WILL BE SET IN RUNTIME"
			}
			env[key] = value
		}
		return nil
	}); err != nil {
		return nil, err
	}
	return env, nil
}
开发者ID:naoina,项目名称:kocha,代码行数:54,代码来源:util.go

示例14: parseFieldOptions

func (c *Connection) parseFieldOptions(tag reflect.StructTag) map[string]interface{} {
	options := make(map[string]interface{})
	optionString := string(tag)

	for optionString != "" {
		// following code is adapted from the golang reflect package
		i := 0
		for i < len(optionString) && optionString[i] == ' ' {
			i++
		}
		optionString = optionString[i:]
		if optionString == "" {
			break
		}

		// scan to colon.
		// a space or a quote is a syntax error
		i = 0
		for i < len(optionString) && optionString[i] != ' ' && optionString[i] != ':' && optionString[i] != '"' {
			i++
		}
		if i+1 >= len(optionString) || optionString[i] != ':' || optionString[i+1] != '"' {
			break
		}
		name := string(optionString[:i])
		optionString = optionString[i+1:]

		// scan quoted string to find value
		i = 1
		for i < len(optionString) && optionString[i] != '"' {
			if optionString[i] == '\\' {
				i++
			}
			i++
		}
		if i >= len(optionString) {
			break
		}
		qvalue := string(optionString[:i+1])
		optionString = optionString[i+1:]

		if name[:2] == "ar" {
			options[name[2:]], _ = strconv.Unquote(qvalue)
		} else {
			options[name[2:]], _ = strconv.Unquote(qvalue)
		}
	}

	return options
}
开发者ID:acsellers,项目名称:db,代码行数:50,代码来源:connection.go

示例15: parseField

// Field = Name Type [ string_lit ] .
//
func (p *parser) parseField(parent *types.Package) (*types.Var, string) {
	pkg, name := p.parseName(parent, true)
	typ := p.parseType(parent)
	anonymous := false
	if name == "" {
		// anonymous field - typ must be T or *T and T must be a type name
		switch typ := deref(typ).(type) {
		case *types.Basic: // basic types are named types
			pkg = nil // objects defined in Universe scope have no package
			name = typ.Name()
		case *types.Named:
			name = typ.Obj().Name()
		default:
			p.errorf("anonymous field expected")
		}
		anonymous = true
	}
	tag := ""
	if p.tok == scanner.String {
		s := p.expect(scanner.String)
		var err error
		tag, err = strconv.Unquote(s)
		if err != nil {
			p.errorf("invalid struct tag %s: %s", s, err)
		}
	}
	return types.NewField(token.NoPos, pkg, name, typ, anonymous), tag
}
开发者ID:vmware,项目名称:vic,代码行数:30,代码来源:gcimporter.go


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