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


Golang strings.Join函数代码示例

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


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

示例1: authenticateChannel

func (c *Client) authenticateChannel(params []byte, member *MemberData) (response []byte, err error) {
	channelName, socketId, err := parseAuthRequestParams(params)

	if err != nil {
		return
	}

	if err = validateSocketId(&socketId); err != nil {
		return
	}

	stringToSign := strings.Join([]string{socketId, channelName}, ":")

	var jsonUserData string

	if member != nil {
		var _jsonUserData []byte
		_jsonUserData, err = json.Marshal(member)
		if err != nil {
			return
		}

		jsonUserData = string(_jsonUserData)
		stringToSign = strings.Join([]string{stringToSign, jsonUserData}, ":")
	}

	_response := createAuthMap(c.Key, c.Secret, stringToSign)

	if member != nil {
		_response["channel_data"] = jsonUserData
	}

	response, err = json.Marshal(_response)
	return
}
开发者ID:vivienschilis,项目名称:pusher-http-go,代码行数:35,代码来源:client.go

示例2: buildURL

// buildURL builds the URL for the operation.
func (s *IndicesExistsTypeService) buildURL() (string, url.Values, error) {
	// Build URL
	path, err := uritemplates.Expand("/{index}/{type}", map[string]string{
		"index": strings.Join(s.index, ","),
		"type":  strings.Join(s.typ, ","),
	})
	if err != nil {
		return "", url.Values{}, err
	}

	// Add query string parameters
	params := url.Values{}
	if s.pretty {
		params.Set("pretty", "1")
	}
	if s.ignoreUnavailable != nil {
		params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable))
	}
	if s.allowNoIndices != nil {
		params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices))
	}
	if s.expandWildcards != "" {
		params.Set("expand_wildcards", s.expandWildcards)
	}
	if s.local != nil {
		params.Set("local", fmt.Sprintf("%v", *s.local))
	}
	return path, params, nil
}
开发者ID:cxytz01,项目名称:heapster,代码行数:30,代码来源:indices_exists_type.go

示例3: buildURL

// buildURL builds the URL for the operation.
func (s *ClusterStateService) buildURL() (string, url.Values, error) {
	// Build URL
	metrics := strings.Join(s.metrics, ",")
	if metrics == "" {
		metrics = "_all"
	}
	indices := strings.Join(s.indices, ",")
	if indices == "" {
		indices = "_all"
	}
	path, err := uritemplates.Expand("/_cluster/state/{metrics}/{indices}", map[string]string{
		"metrics": metrics,
		"indices": indices,
	})
	if err != nil {
		return "", url.Values{}, err
	}

	// Add query string parameters
	params := url.Values{}
	if s.masterTimeout != "" {
		params.Set("master_timeout", s.masterTimeout)
	}
	if s.flatSettings != nil {
		params.Set("flat_settings", fmt.Sprintf("%v", *s.flatSettings))
	}
	if s.local != nil {
		params.Set("local", fmt.Sprintf("%v", *s.local))
	}

	return path, params, nil
}
开发者ID:eswdd,项目名称:bosun,代码行数:33,代码来源:cluster_state.go

示例4: createTableSql

func (hood *Hood) createTableSql(model *Model) string {
	a := []string{"CREATE TABLE ", model.Table, " ( "}
	for i, field := range model.Fields {
		b := []string{
			field.Name,
			hood.Dialect.SqlType(field.Value, field.Size()),
		}
		if field.NotNull() {
			b = append(b, hood.Dialect.KeywordNotNull())
		}
		if x := field.Default(); x != "" {
			b = append(b, hood.Dialect.KeywordDefault(x))
		}
		if field.PrimaryKey() {
			b = append(b, hood.Dialect.KeywordPrimaryKey())
		}
		if incKeyword := hood.Dialect.KeywordAutoIncrement(); field.PrimaryKey() && incKeyword != "" {
			b = append(b, incKeyword)
		}
		a = append(a, strings.Join(b, " "))
		if i < len(model.Fields)-1 {
			a = append(a, ", ")
		}
	}
	a = append(a, " )")

	return strings.Join(a, "")
}
开发者ID:timdufrane,项目名称:hood,代码行数:28,代码来源:mapper.go

示例5: verifyCPULimits

func verifyCPULimits(expected framework.ContainersCPUSummary, actual framework.NodesCPUSummary) {
	if expected == nil {
		return
	}
	var errList []string
	for nodeName, perNodeSummary := range actual {
		var nodeErrs []string
		for cName, expectedResult := range expected {
			perContainerSummary, ok := perNodeSummary[cName]
			if !ok {
				nodeErrs = append(nodeErrs, fmt.Sprintf("container %q: missing", cName))
				continue
			}
			for p, expectedValue := range expectedResult {
				actualValue, ok := perContainerSummary[p]
				if !ok {
					nodeErrs = append(nodeErrs, fmt.Sprintf("container %q: missing percentile %v", cName, p))
					continue
				}
				if actualValue > expectedValue {
					nodeErrs = append(nodeErrs, fmt.Sprintf("container %q: expected %.0fth%% usage < %.3f; got %.3f",
						cName, p*100, expectedValue, actualValue))
				}
			}
		}
		if len(nodeErrs) > 0 {
			errList = append(errList, fmt.Sprintf("node %v:\n %s", nodeName, strings.Join(nodeErrs, ", ")))
		}
	}
	if len(errList) > 0 {
		framework.Failf("CPU usage exceeding limits:\n %s", strings.Join(errList, "\n"))
	}
}
开发者ID:upmc-enterprises,项目名称:kubernetes,代码行数:33,代码来源:kubelet_perf.go

示例6: cors

// cors responds to incoming requests and adds the appropriate cors headers
// TODO: corylanou: add the ability to configure this in our config
func cors(inner http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if origin := r.Header.Get("Origin"); origin != "" {
			w.Header().Set(`Access-Control-Allow-Origin`, origin)
			w.Header().Set(`Access-Control-Allow-Methods`, strings.Join([]string{
				`DELETE`,
				`GET`,
				`OPTIONS`,
				`POST`,
				`PUT`,
			}, ", "))

			w.Header().Set(`Access-Control-Allow-Headers`, strings.Join([]string{
				`Accept`,
				`Accept-Encoding`,
				`Authorization`,
				`Content-Length`,
				`Content-Type`,
				`X-CSRF-Token`,
				`X-HTTP-Method-Override`,
			}, ", "))
		}

		if r.Method == "OPTIONS" {
			return
		}

		inner.ServeHTTP(w, r)
	})
}
开发者ID:pcn,项目名称:influxdb,代码行数:32,代码来源:handler.go

示例7: Add

// Adds a hook script.
func Add(name string, repos []string, body io.Reader) error {
	config_param := "git:bare:template"
	if len(repos) > 0 {
		config_param = "git:bare:location"
	}
	path, err := config.GetString(config_param)
	if err != nil {
		return err
	}
	s := []string{path, "hooks", name}
	scriptPath := strings.Join(s, "/")
	if len(repos) > 0 {
		for _, repo := range repos {
			repo += ".git"
			s = []string{path, repo, "hooks", name}
			scriptPath = strings.Join(s, "/")
			err := createHookFile(scriptPath, body)
			if err != nil {
				return err
			}
		}
	} else {
		return createHookFile(scriptPath, body)
	}
	return nil
}
开发者ID:rfloriano,项目名称:gandalf,代码行数:27,代码来源:hook.go

示例8: init

func init() {
	//	log.SetFlags(log.Ltime | log.Lmicroseconds | log.Lshortfile)
	log.SetFlags(log.Lshortfile)

	vizList := ""
	vizHelp := "Visualize: all,none,useful"
	for flag := range Viz {
		vizHelp += "," + flag
	}

	flag.StringVar(&runBot, "b", "v8", "Which bot to run\n\t"+strings.Join(BotList(), "\n\t"))
	flag.StringVar(&vizList, "V", "", vizHelp)
	flag.IntVar(&debugLevel, "d", 0, "Debug level")
	flag.StringVar(&mapName, "m", "", "Map file -- Used to validate generated map, hill guessing etc.")
	flag.StringVar(&watchPoints, "w", "", "Watch points \"T1:[email protected],C,N[;T1:T2...]\", \":\" will watch everything")
	flag.IntVar(&maxTurn, "T", 65535, "Max Turn")
	flag.Parse()

	if BotGet(runBot) == nil {
		log.Printf("Unrecognized bot \"%s\", Registered bots:\n\t%s\n", runBot, strings.Join(BotList(), "\n\t"))
		return
	}

	SetWatcherPrefix(runBot)

	SetDebugLevel(debugLevel)
	SetViz(vizList, Viz)
}
开发者ID:jcdny,项目名称:bugnuts,代码行数:28,代码来源:main.go

示例9: sign

func sign(auth aws.Auth, method, path string, params url.Values, headers http.Header) {
	var host string
	for k, v := range headers {
		k = strings.ToLower(k)
		switch k {
		case "host":
			host = v[0]
		}
	}

	// set up some defaults used for signing the request
	params["AWSAccessKeyId"] = []string{auth.AccessKey}
	params["SignatureVersion"] = []string{"2"}
	params["SignatureMethod"] = []string{"HmacSHA256"}

	// join up all the incoming params
	var sarray []string
	for k, v := range params {
		sarray = append(sarray, aws.Encode(k)+"="+aws.Encode(v[0]))
	}
	sort.StringSlice(sarray).Sort()
	joined := strings.Join(sarray, "&")

	// create the payload, sign it and create the signature
	payload := strings.Join([]string{method, host, "/", joined}, "\n")
	hash := hmac.New(sha256.New, []byte(auth.SecretKey))
	hash.Write([]byte(payload))
	signature := make([]byte, b64.EncodedLen(hash.Size()))
	b64.Encode(signature, hash.Sum(nil))

	// add the signature to the outgoing params
	params["Signature"] = []string{string(signature)}
}
开发者ID:koofr,项目名称:goamz,代码行数:33,代码来源:sign.go

示例10: generatePreflightHeaders

func generatePreflightHeaders(c Config) http.Header {
	headers := make(http.Header)
	if c.AllowCredentials {
		headers.Set("Access-Control-Allow-Credentials", "true")
	}
	if len(c.AllowMethods) > 0 {
		allowMethods := convert(normalize(c.AllowMethods), strings.ToUpper)
		value := strings.Join(allowMethods, ",")
		headers.Set("Access-Control-Allow-Methods", value)
	}
	if len(c.AllowHeaders) > 0 {
		allowHeaders := convert(normalize(c.AllowHeaders), http.CanonicalHeaderKey)
		value := strings.Join(allowHeaders, ",")
		headers.Set("Access-Control-Allow-Headers", value)
	}
	if c.MaxAge > time.Duration(0) {
		value := strconv.FormatInt(int64(c.MaxAge/time.Second), 10)
		headers.Set("Access-Control-Max-Age", value)
	}
	if c.AllowAllOrigins {
		headers.Set("Access-Control-Allow-Origin", "*")
	} else {
		// Always set Vary headers
		// see https://github.com/rs/cors/issues/10,
		// https://github.com/rs/cors/commit/dbdca4d95feaa7511a46e6f1efb3b3aa505bc43f#commitcomment-12352001

		headers.Add("Vary", "Origin")
		headers.Add("Vary", "Access-Control-Request-Method")
		headers.Add("Vary", "Access-Control-Request-Headers")
	}
	return headers
}
开发者ID:gin-contrib,项目名称:cors,代码行数:32,代码来源:utils.go

示例11: runListUnits

func runListUnits(args []string) (exit int) {
	if listUnitsFieldsFlag == "" {
		stderr("Must define output format")
		return 1
	}

	cols := strings.Split(listUnitsFieldsFlag, ",")
	for _, s := range cols {
		if _, ok := listUnitsFields[s]; !ok {
			stderr("Invalid key in output format: %q", s)
			return 1
		}
	}

	states, err := cAPI.UnitStates()
	if err != nil {
		stderr("Error retrieving list of units from repository: %v", err)
		return 1
	}

	if !sharedFlags.NoLegend {
		fmt.Fprintln(out, strings.ToUpper(strings.Join(cols, "\t")))
	}

	for _, us := range states {
		var f []string
		for _, c := range cols {
			f = append(f, listUnitsFields[c](us, sharedFlags.Full))
		}
		fmt.Fprintln(out, strings.Join(f, "\t"))
	}

	out.Flush()
	return
}
开发者ID:ericcapricorn,项目名称:fleet,代码行数:35,代码来源:list_units.go

示例12: runCommand

func runCommand(name string, args ...string) error {
	glog.Infof("Running command: %v %v", name, strings.Join(args, " "))
	cmd := exec.Command("sh", "-c", strings.Join(append([]string{name}, args...), " "))
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	return cmd.Run()
}
开发者ID:ncdc,项目名称:kubernetes,代码行数:7,代码来源:run_local.go

示例13: normalizeRegistry

func normalizeRegistry(address string) string {
	logger := util.RootLogger().WithField("Logger", "Docker")
	if address == "" {
		logger.Debugln("No registry address provided, using https://registry.hub.docker.com")
		return "https://registry.hub.docker.com/v1/"
	}
	parsed, err := url.Parse(address)
	if err != nil {
		logger.Errorln("Registry address is invalid, this will probably fail:", address)
		return address
	}
	if parsed.Scheme != "https" {
		logger.Warnln("Registry address is expected to begin with 'https://', forcing it to use https")
		parsed.Scheme = "https"
		address = parsed.String()
	}
	if strings.HasSuffix(address, "/") {
		address = address[:len(address)-1]
	}

	parts := strings.Split(address, "/")
	possiblyAPIVersionStr := parts[len(parts)-1]

	// we only support v1, so...
	if possiblyAPIVersionStr == "v2" {
		logger.Warnln("Registry API v2 not supported, using v1")
		newParts := append(parts[:len(parts)-1], "v1")
		address = strings.Join(newParts, "/")
	} else if possiblyAPIVersionStr != "v1" {
		newParts := append(parts, "v1")
		address = strings.Join(newParts, "/")
	}
	return address + "/"
}
开发者ID:rlugojr,项目名称:wercker,代码行数:34,代码来源:docker.go

示例14: whereEqMap

func whereEqMap(m map[string]interface{}) (sql string, args []interface{}, err error) {
	var exprs []string
	for key, val := range m {
		expr := ""
		if val == nil {
			expr = fmt.Sprintf("%s IS NULL", key)
		} else {
			valVal := reflect.ValueOf(val)
			if valVal.Kind() == reflect.Array || valVal.Kind() == reflect.Slice {
				placeholders := make([]string, valVal.Len())
				for i := 0; i < valVal.Len(); i++ {
					placeholders[i] = "?"
					args = append(args, valVal.Index(i).Interface())
				}
				placeholdersStr := strings.Join(placeholders, ",")
				expr = fmt.Sprintf("%s IN (%s)", key, placeholdersStr)
			} else {
				expr = fmt.Sprintf("%s = ?", key)
				args = append(args, val)
			}
		}
		exprs = append(exprs, expr)
	}
	sql = strings.Join(exprs, " AND ")
	return
}
开发者ID:nizsheanez,项目名称:squirrel,代码行数:26,代码来源:where.go

示例15: formatTable

func (cmd *esxcli) formatTable(res *Response) {
	fields := res.Info.Hints.Fields()

	tw := tabwriter.NewWriter(os.Stdout, len(fields), 0, 2, ' ', 0)

	var hr []string
	for _, name := range fields {
		hr = append(hr, strings.Repeat("-", len(name)))
	}

	fmt.Fprintln(tw, strings.Join(fields, "\t"))
	fmt.Fprintln(tw, strings.Join(hr, "\t"))

	for _, vals := range res.Values {
		var row []string

		for _, name := range fields {
			key := strings.Replace(name, " ", "", -1)
			if val, ok := vals[key]; ok {
				row = append(row, strings.Join(val, ", "))
			} else {
				row = append(row, "")
			}
		}

		fmt.Fprintln(tw, strings.Join(row, "\t"))
	}

	_ = tw.Flush()
}
开发者ID:Tiger66639,项目名称:jupiter-brain,代码行数:30,代码来源:esxcli.go


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