本文整理匯總了Golang中fmt.Sprintf函數的典型用法代碼示例。如果您正苦於以下問題:Golang Sprintf函數的具體用法?Golang Sprintf怎麽用?Golang Sprintf使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Sprintf函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: describeServicePorts
func describeServicePorts(spec kapi.ServiceSpec) string {
switch len(spec.Ports) {
case 0:
return " no ports"
case 1:
port := portOrNodePort(spec, spec.Ports[0])
if spec.Ports[0].TargetPort.String() == "0" || spec.ClusterIP == kapi.ClusterIPNone || port == spec.Ports[0].TargetPort.String() {
return fmt.Sprintf(":%s", port)
}
return fmt.Sprintf(":%s -> %s", port, spec.Ports[0].TargetPort.String())
default:
pairs := []string{}
for _, port := range spec.Ports {
externalPort := portOrNodePort(spec, port)
if port.TargetPort.String() == "0" || spec.ClusterIP == kapi.ClusterIPNone {
pairs = append(pairs, externalPort)
continue
}
if port.Port == int(port.TargetPort.IntVal) {
pairs = append(pairs, port.TargetPort.String())
} else {
pairs = append(pairs, fmt.Sprintf("%s->%s", externalPort, port.TargetPort.String()))
}
}
return " ports " + strings.Join(pairs, ", ")
}
}
示例2: Tr
// Tr translate content to target language.
func Tr(lang, format string, args ...interface{}) string {
var section string
parts := strings.SplitN(format, ".", 2)
if len(parts) == 2 {
section = parts[0]
format = parts[1]
}
value, ok := locales.Get(lang, section, format)
if ok {
format = value
}
if len(args) > 0 {
params := make([]interface{}, 0, len(args))
for _, arg := range args {
if arg != nil {
val := reflect.ValueOf(arg)
if val.Kind() == reflect.Slice {
for i := 0; i < val.Len(); i++ {
params = append(params, val.Index(i).Interface())
}
} else {
params = append(params, arg)
}
}
}
return fmt.Sprintf(format, params...)
}
return fmt.Sprintf(format)
}
示例3: RenderSpecialLink
func RenderSpecialLink(rawBytes []byte, urlPrefix string) []byte {
ms := MentionPattern.FindAll(rawBytes, -1)
for _, m := range ms {
rawBytes = bytes.Replace(rawBytes, m,
[]byte(fmt.Sprintf(`<a href="/user/%s">%s</a>`, m[1:], m)), -1)
}
ms = commitPattern.FindAll(rawBytes, -1)
for _, m := range ms {
m = bytes.TrimSpace(m)
i := strings.Index(string(m), "commit/")
j := strings.Index(string(m), "#")
if j == -1 {
j = len(m)
}
rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
` <code><a href="%s">%s</a></code>`, m, ShortSha(string(m[i+7:j])))), -1)
}
ms = issueFullPattern.FindAll(rawBytes, -1)
for _, m := range ms {
m = bytes.TrimSpace(m)
i := strings.Index(string(m), "issues/")
j := strings.Index(string(m), "#")
if j == -1 {
j = len(m)
}
rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
` <a href="%s">#%s</a>`, m, ShortSha(string(m[i+7:j])))), -1)
}
ms = issueIndexPattern.FindAll(rawBytes, -1)
for _, m := range ms {
rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
`<a href="%s/issues/%s">%s</a>`, urlPrefix, m[1:], m)), -1)
}
return rawBytes
}
示例4: validateDefaultValueSchemaAgainstSchema
func (s *SpecValidator) validateDefaultValueSchemaAgainstSchema(path, in string, schema *spec.Schema) *Result {
res := new(Result)
if schema != nil {
if schema.Default != nil {
res.Merge(NewSchemaValidator(schema, s.spec.Spec(), path, s.KnownFormats).Validate(schema.Default))
}
if schema.Items != nil {
if schema.Items.Schema != nil {
res.Merge(s.validateDefaultValueSchemaAgainstSchema(path+".items", in, schema.Items.Schema))
}
for i, sch := range schema.Items.Schemas {
res.Merge(s.validateDefaultValueSchemaAgainstSchema(fmt.Sprintf("%s.items[%d]", path, i), in, &sch))
}
}
if schema.AdditionalItems != nil && schema.AdditionalItems.Schema != nil {
res.Merge(s.validateDefaultValueSchemaAgainstSchema(fmt.Sprintf("%s.additionalItems", path), in, schema.AdditionalItems.Schema))
}
for propName, prop := range schema.Properties {
res.Merge(s.validateDefaultValueSchemaAgainstSchema(path+"."+propName, in, &prop))
}
for propName, prop := range schema.PatternProperties {
res.Merge(s.validateDefaultValueSchemaAgainstSchema(path+"."+propName, in, &prop))
}
if schema.AdditionalProperties != nil && schema.AdditionalProperties.Schema != nil {
res.Merge(s.validateDefaultValueSchemaAgainstSchema(fmt.Sprintf("%s.additionalProperties", path), in, schema.AdditionalProperties.Schema))
}
for i, aoSch := range schema.AllOf {
res.Merge(s.validateDefaultValueSchemaAgainstSchema(fmt.Sprintf("%s.allOf[%d]", path, i), in, &aoSch))
}
}
return res
}
示例5: Run
// Run runs the the tunnel session
func (s *Session) Run() (err error) {
defer s.recoverPanic("Session.Run")
go func() {
defer s.recoverPanic("Session.mux.Wait")
code, err, debug1 := s.mux.Wait()
// s.Info("Session mux shutdown with code %v error %v debug %v", code, err, debug)
log.Println(fmt.Sprintf("[INFO] Session mux shutdown with code %v error %v debug %v", code, err, debug1))
}()
defer s.mux.Close()
// A tunnel session starts with an auth stream
if err = s.handleAuth(); err != nil {
return
}
// then we handle new streams sent from the client
for {
stream, err := s.mux.Accept()
if err != nil {
s.Shutdown()
err := fmt.Errorf(fmt.Sprintf("Failed to accept stream: %v", err))
log.Println(fmt.Sprintf("[ERROR] %v", err))
return err
}
go s.handleStream(conn.Wrap(stream, "stream", s.id))
}
}
示例6: newRepo
func newRepo(name string, simpleDocker SimpleDocker.SimpleDocker) (Repo, error) {
log.WithFields(log.Fields{
"name": name,
}).Info("Creating new repo")
r := Repo{
Name: name,
SimpleDocker: simpleDocker,
}
startTime := time.Now()
repoName := fmt.Sprintf("ihsw/%s", name)
if err := r.pullImage(repoName); err != nil {
log.WithFields(log.Fields{
"name": name,
"err": err.Error(),
"repoName": repoName,
}).Warn("Could not pull image")
return Repo{}, err
}
log.WithFields(log.Fields{
"name": name,
"duration": fmt.Sprintf("%v", time.Now().Sub(startTime)),
}).Info("Repo create success")
return r, nil
}
示例7: buildURL
// buildURL builds the URL for the operation.
func (s *IndicesGetTemplateService) buildURL() (string, url.Values, error) {
// Build URL
var err error
var path string
if len(s.name) > 0 {
path, err = uritemplates.Expand("/_template/{name}", map[string]string{
"name": strings.Join(s.name, ","),
})
} else {
path = "/_template"
}
if err != nil {
return "", url.Values{}, err
}
// Add query string parameters
params := url.Values{}
if s.pretty {
params.Set("pretty", "1")
}
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
}
示例8: Dot
func (f *Field) Dot() string {
s := "digraph G {\n"
// nodes
for _, n := range *f {
s += fmt.Sprintf(
"\t%s [shape=box,label=\"%s\"];\n",
n.Name(),
NodeLabel(n),
//n,
)
}
s += "\n"
// edges
for _, n := range *f {
D("Dot: adding edges for %d children of %s", len(n.Children()), n.Name())
for _, child := range n.Children() {
s += fmt.Sprintf("\t%s -> %s;\n", n.Name(), child.Name())
}
}
s += "}"
return s
}
示例9: Error
func (e *exitError) Error() string {
if e.cause != nil {
return fmt.Sprintf("task: non-zero exit (%v): %v", e.code, e.cause)
}
return fmt.Sprintf("task: non-zero exit (%v)", e.code)
}
示例10: describeDeployments
func describeDeployments(f formatter, dcNode *deploygraph.DeploymentConfigNode, activeDeployment *kubegraph.ReplicationControllerNode, inactiveDeployments []*kubegraph.ReplicationControllerNode, count int) []string {
if dcNode == nil {
return nil
}
out := []string{}
deploymentsToPrint := append([]*kubegraph.ReplicationControllerNode{}, inactiveDeployments...)
if activeDeployment == nil {
on, auto := describeDeploymentConfigTriggers(dcNode.DeploymentConfig)
if dcNode.DeploymentConfig.Status.LatestVersion == 0 {
out = append(out, fmt.Sprintf("deployment #1 waiting %s", on))
} else if auto {
out = append(out, fmt.Sprintf("deployment #%d pending %s", dcNode.DeploymentConfig.Status.LatestVersion, on))
}
// TODO: detect new image available?
} else {
deploymentsToPrint = append([]*kubegraph.ReplicationControllerNode{activeDeployment}, inactiveDeployments...)
}
for i, deployment := range deploymentsToPrint {
out = append(out, describeDeploymentStatus(deployment.ReplicationController, i == 0, dcNode.DeploymentConfig.Spec.Test))
switch {
case count == -1:
if deployutil.DeploymentStatusFor(deployment) == deployapi.DeploymentStatusComplete {
return out
}
default:
if i+1 >= count {
return out
}
}
}
return out
}
示例11: TestMountMoreThan42Layers
func TestMountMoreThan42Layers(t *testing.T) {
d := newDriver(t)
defer os.RemoveAll(tmp)
defer d.Cleanup()
var last string
var expected int
for i := 1; i < 127; i++ {
expected++
var (
parent = fmt.Sprintf("%d", i-1)
current = fmt.Sprintf("%d", i)
)
if parent == "0" {
parent = ""
} else {
parent = hash(parent)
}
current = hash(current)
if err := d.Create(current, parent); err != nil {
t.Logf("Current layer %d", i)
t.Fatal(err)
}
point, err := d.Get(current)
if err != nil {
t.Logf("Current layer %d", i)
t.Fatal(err)
}
f, err := os.Create(path.Join(point, current))
if err != nil {
t.Logf("Current layer %d", i)
t.Fatal(err)
}
f.Close()
if i%10 == 0 {
if err := os.Remove(path.Join(point, parent)); err != nil {
t.Logf("Current layer %d", i)
t.Fatal(err)
}
expected--
}
last = current
}
// Perform the actual mount for the top most image
point, err := d.Get(last)
if err != nil {
t.Fatal(err)
}
files, err := ioutil.ReadDir(point)
if err != nil {
t.Fatal(err)
}
if len(files) != expected {
t.Fatalf("Expected %d got %d", expected, len(files))
}
}
示例12: describeRouteInServiceGroup
func describeRouteInServiceGroup(f formatter, routeNode *routegraph.RouteNode) []string {
// markers should cover printing information about admission failure
requested, other, errors := extractRouteInfo(routeNode.Route)
var lines []string
if requested {
lines = append(lines, describeRouteExposed(routeNode.Spec.Host, routeNode.Route, len(errors) > 0))
}
for _, s := range other {
lines = append(lines, describeRouteExposed(s, routeNode.Route, len(errors) > 0))
}
if len(lines) == 0 {
switch {
case len(errors) >= 1:
// router rejected the output
lines = append(lines, fmt.Sprintf("%s not accepted: %s", f.ResourceName(routeNode), errors[0]))
case len(routeNode.Spec.Host) == 0:
// no errors or output, likely no router running and no default domain
lines = append(lines, fmt.Sprintf("%s has no host set", f.ResourceName(routeNode)))
case len(routeNode.Status.Ingress) == 0:
// host set, but no ingress, an older legacy router
lines = append(lines, describeRouteExposed(routeNode.Spec.Host, routeNode.Route, false))
default:
// multiple conditions but no host exposed, use the generic legacy output
lines = append(lines, fmt.Sprintf("exposed as %s by %s", routeNode.Spec.Host, f.ResourceName(routeNode)))
}
}
return lines
}
示例13: describeDeploymentInServiceGroup
func describeDeploymentInServiceGroup(f formatter, deploy graphview.DeploymentConfigPipeline) []string {
local := namespacedFormatter{currentNamespace: deploy.Deployment.Namespace}
includeLastPass := deploy.ActiveDeployment == nil
if len(deploy.Images) == 1 {
format := "%s deploys %s %s"
if deploy.Deployment.Spec.Test {
format = "%s test deploys %s %s"
}
lines := []string{fmt.Sprintf(format, f.ResourceName(deploy.Deployment), describeImageInPipeline(local, deploy.Images[0], deploy.Deployment.Namespace), describeDeploymentConfigTrigger(deploy.Deployment.DeploymentConfig))}
if len(lines[0]) > 120 && strings.Contains(lines[0], " <- ") {
segments := strings.SplitN(lines[0], " <- ", 2)
lines[0] = segments[0] + " <-"
lines = append(lines, segments[1])
}
lines = append(lines, indentLines(" ", describeAdditionalBuildDetail(deploy.Images[0].Build, deploy.Images[0].LastSuccessfulBuild, deploy.Images[0].LastUnsuccessfulBuild, deploy.Images[0].ActiveBuilds, deploy.Images[0].DestinationResolved, includeLastPass)...)...)
lines = append(lines, describeDeployments(local, deploy.Deployment, deploy.ActiveDeployment, deploy.InactiveDeployments, 3)...)
return lines
}
format := "%s deploys %s"
if deploy.Deployment.Spec.Test {
format = "%s test deploys %s"
}
lines := []string{fmt.Sprintf(format, f.ResourceName(deploy.Deployment), describeDeploymentConfigTrigger(deploy.Deployment.DeploymentConfig))}
for _, image := range deploy.Images {
lines = append(lines, describeImageInPipeline(local, image, deploy.Deployment.Namespace))
lines = append(lines, indentLines(" ", describeAdditionalBuildDetail(image.Build, image.LastSuccessfulBuild, image.LastUnsuccessfulBuild, image.ActiveBuilds, image.DestinationResolved, includeLastPass)...)...)
lines = append(lines, describeDeployments(local, deploy.Deployment, deploy.ActiveDeployment, deploy.InactiveDeployments, 3)...)
}
return lines
}
示例14: describeProjectAndServer
func describeProjectAndServer(f formatter, project *projectapi.Project, server string) string {
if len(server) == 0 {
return fmt.Sprintf("In project %s on server %s\n", projectapi.DisplayNameAndNameForProject(project), server)
}
return fmt.Sprintf("In project %s on server %s\n", projectapi.DisplayNameAndNameForProject(project), server)
}
示例15: Check
func (checker *codecEqualChecker) Check(params []interface{}, names []string) (result bool, error string) {
gotContent, ok := params[0].(string)
if !ok {
return false, fmt.Sprintf("expected string, got %T", params[0])
}
expectContent := params[1]
expectContentBytes, err := checker.marshal(expectContent)
if err != nil {
return false, fmt.Sprintf("cannot marshal expected contents: %v", err)
}
var expectContentVal interface{}
if err := checker.unmarshal(expectContentBytes, &expectContentVal); err != nil {
return false, fmt.Sprintf("cannot unmarshal expected contents: %v", err)
}
var gotContentVal interface{}
if err := checker.unmarshal([]byte(gotContent), &gotContentVal); err != nil {
return false, fmt.Sprintf("cannot unmarshal obtained contents: %v; %q", err, gotContent)
}
if ok, err := DeepEqual(gotContentVal, expectContentVal); !ok {
return false, err.Error()
}
return true, ""
}