本文整理匯總了Golang中fmt.Sprint函數的典型用法代碼示例。如果您正苦於以下問題:Golang Sprint函數的具體用法?Golang Sprint怎麽用?Golang Sprint使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Sprint函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: PrintMapRecursive
// PrintMap prints a map - recursing through submaps
// concrete types, like map[float64]map[int]float64
// would have to be converted element by element
// to map[interface{}]interface{}
// the json.indent function might be similar
// but I did not bring it to work
func PrintMapRecursive(m1 map[interface{}]interface{}, depth int) string {
b1 := new(bytes.Buffer)
fiveSpaces := " " // html spaces
cxIndent := fmt.Sprint(depth * 40)
depthStyle := ""
if depth == 0 {
depthStyle = "margin-top:8px; border-top: 1px solid #aaa;"
} else {
darkening := 16 - 2*depth
bgc := fmt.Sprintf("%x%x%x", darkening, darkening, darkening)
depthStyle = "margin:0;padding:0;background-color:#" + bgc + ";"
}
for k1, m2 := range m1 {
b1.WriteString("<div style='" + depthStyle + "margin-left:" + cxIndent + "px;'>\n")
b1.WriteString(fmt.Sprint(k1))
//b1.WriteString( "<br>\n" )
switch typedvar := m2.(type) {
default:
type_unknown := fmt.Sprintf("<br>\n --this type switch does not support type %#v", typedvar)
//panic(type_unknown)
b1.WriteString(fiveSpaces + fmt.Sprintf("%#v", typedvar) + type_unknown)
case string:
b1.WriteString(fiveSpaces + typedvar)
case int, float64:
b1.WriteString(fiveSpaces + fmt.Sprint(typedvar))
case nil:
b1.WriteString("nil interface")
case map[interface{}]interface{}:
b1.WriteString(PrintMapRecursive(typedvar, depth+1))
}
b1.WriteString("<br>\n")
b1.WriteString("</div>\n")
}
return b1.String()
}
示例2: Panic
func (entry *Entry) Panic(args ...interface{}) {
if entry.Logger.Level >= Panic {
msg := entry.log("panic", Panic, fmt.Sprint(args...))
panic(msg)
}
panic(fmt.Sprint(args...))
}
示例3: DescribeCdnDomainBaseDetail
// DescribeCdnDomainBaseDetail version 2014-11-11
//
// required parameters:
// name: DomainName, type: string
//
// optional parameters:
// name: OwnerId, type: int64
// name: ResourceOwnerAccount, type: string
// name: ResourceOwnerId, type: int64
// name: _method, type: string, optional values: GET|POST
// name: _region, type: string
// name: _scheme, type: string, optional values: http|https
func (api API) DescribeCdnDomainBaseDetail(DomainName string, optional openapi.M) (*DescribeCdnDomainBaseDetailResponse, error) {
args := NewParams()
args.Query.Set("Action", "DescribeCdnDomainBaseDetail")
args.Query.Set("DomainName", DomainName)
if v, ok := optional["OwnerId"]; ok {
if OwnerId, ok := v.(int64); ok {
args.Query.Set("OwnerId", fmt.Sprint(OwnerId))
} else {
return nil, errors.New("OwnerId must be int64")
}
}
if v, ok := optional["ResourceOwnerAccount"]; ok {
if ResourceOwnerAccount, ok := v.(string); ok {
args.Query.Set("ResourceOwnerAccount", ResourceOwnerAccount)
} else {
return nil, errors.New("ResourceOwnerAccount must be string")
}
}
if v, ok := optional["ResourceOwnerId"]; ok {
if ResourceOwnerId, ok := v.(int64); ok {
args.Query.Set("ResourceOwnerId", fmt.Sprint(ResourceOwnerId))
} else {
return nil, errors.New("ResourceOwnerId must be int64")
}
}
if v, ok := optional["_method"]; ok {
if s, ok := v.(string); ok {
if !openapi.IsIn(s, "GET|POST") {
return nil, errors.New("_method must be GET|POST")
}
args.Method = s
} else {
return nil, errors.New("_method must be string")
}
}
if v, ok := optional["_region"]; ok {
if s, ok := v.(string); ok {
args.Region = s
} else {
return nil, errors.New("_region must be string")
}
}
if v, ok := optional["_scheme"]; ok {
if s, ok := v.(string); ok {
if !openapi.IsIn(s, "http|https") {
return nil, errors.New("_scheme must be http|https")
}
args.Scheme = s
} else {
return nil, errors.New("_scheme must be string")
}
}
result := new(DescribeCdnDomainBaseDetailResponse)
if err := api.Service.Do(result, args); err != nil {
return nil, err
}
return result, nil
}
示例4: parseGauges
func parseGauges(info string) map[string]int64 {
gauges_with_values := map[string]int64{
"blocked_clients": 0,
"connected_clients": 0,
"instantaneous_ops_per_sec": 0,
"latest_fork_usec": 0,
"mem_fragmentation_ratio": 0,
"migrate_cached_sockets": 0,
"pubsub_channels": 0,
"pubsub_patterns": 0,
"uptime_in_seconds": 0,
"used_memory": 0,
"used_memory_lua": 0,
"used_memory_peak": 0,
"used_memory_rss": 0,
}
color.White("-------------------")
color.White("GAUGES:")
for gauge, _ := range gauges_with_values {
r, _ := regexp.Compile(fmt.Sprint(gauge, ":([0-9]*)"))
matches := r.FindStringSubmatch(info)
if matches == nil {
color.Yellow(fmt.Sprint("WARN: ", gauge, "is not displayed in redis info"))
} else {
value := matches[len(matches)-1]
color.Cyan(fmt.Sprint(gauge, ": ", value))
v, _ := strconv.ParseInt(value, 10, 64)
gauges_with_values[gauge] = v
}
}
return gauges_with_values
}
示例5: TestStatic
func TestStatic(t *testing.T) {
var (
instances = []string{"foo", "bar", "baz"}
endpoints = map[string]endpoint.Endpoint{
"foo": func(context.Context, interface{}) (interface{}, error) { return struct{}{}, nil },
"bar": func(context.Context, interface{}) (interface{}, error) { return struct{}{}, nil },
"baz": func(context.Context, interface{}) (interface{}, error) { return struct{}{}, nil },
}
factory = func(instance string) (endpoint.Endpoint, error) {
if e, ok := endpoints[instance]; ok {
return e, nil
}
return nil, fmt.Errorf("%s: not found", instance)
}
)
p := static.NewPublisher(instances, factory, log.NewNopLogger())
have, err := p.Endpoints()
if err != nil {
t.Fatal(err)
}
want := []endpoint.Endpoint{endpoints["foo"], endpoints["bar"], endpoints["baz"]}
if fmt.Sprint(want) != fmt.Sprint(have) {
t.Fatalf("want %v, have %v", want, have)
}
}
示例6: InsertWithUID
func InsertWithUID(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "application/json")
var col, doc string
if !Require(w, r, "col", &col) {
return
}
if !Require(w, r, "doc", &doc) {
return
}
V3Sync.RLock()
defer V3Sync.RUnlock()
dbcol := V3DB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
var jsonDoc interface{}
if err := json.Unmarshal([]byte(doc), &jsonDoc); err != nil {
http.Error(w, fmt.Sprintf("'%v' is not valid JSON document.", doc), 400)
return
}
id, uid, err := dbcol.InsertWithUID(jsonDoc)
if err != nil {
http.Error(w, fmt.Sprint(err), 500)
return
}
resp, err := json.Marshal(map[string]interface{}{"id": id, "uid": uid})
if err != nil {
http.Error(w, fmt.Sprint(err), 500)
return
}
w.WriteHeader(201)
w.Write(resp)
}
示例7: viewInvite
func viewInvite(w http.ResponseWriter, r *http.Request) {
mail := r.PostFormValue("mail")
conf, err := loadConf()
if err != nil {
log.Fatalln(err)
}
client := &http.Client{}
data := url.Values{
"email": {mail},
"token": {conf.Token},
"set_active": {"true"},
}
resp, err := client.Post(
"https://"+conf.URL+"/api/users.admin.invite",
"application/x-www-form-urlencoded",
strings.NewReader(data.Encode()),
)
if err != nil {
log.Fatalln(err)
}
body, _ := ioutil.ReadAll(resp.Body)
var status map[string]interface{}
json.Unmarshal(body, &status)
fmt.Println(status["ok"])
statusOk := fmt.Sprint(status["ok"])
if statusOk == "true" {
fmt.Fprintf(w, mail+"に招待狀を送信しました.")
} else {
fmt.Fprintf(w, "失敗した。失敗した。失敗した。"+fmt.Sprint(status["error"]))
}
}
示例8: String
func (m *Map) String() string {
s := "Map [" + fmt.Sprint(m.width) + " x " + fmt.Sprint(m.height) + "]\n{"
for _, ap := range m.accessPoints {
s += ap.String() + ", "
}
return s + "}"
}
示例9: TestUpdateToInvalid
func TestUpdateToInvalid(t *testing.T) {
ldb := db.OpenMemory()
s := db.NewFileSet("test", ldb)
localHave := fileList{
protocol.FileInfo{Name: "a", Version: protocol.Vector{Counters: []protocol.Counter{{ID: myID, Value: 1000}}}, Blocks: genBlocks(1)},
protocol.FileInfo{Name: "b", Version: protocol.Vector{Counters: []protocol.Counter{{ID: myID, Value: 1001}}}, Blocks: genBlocks(2)},
protocol.FileInfo{Name: "c", Version: protocol.Vector{Counters: []protocol.Counter{{ID: myID, Value: 1002}}}, Blocks: genBlocks(5), Invalid: true},
protocol.FileInfo{Name: "d", Version: protocol.Vector{Counters: []protocol.Counter{{ID: myID, Value: 1003}}}, Blocks: genBlocks(7)},
}
s.Replace(protocol.LocalDeviceID, localHave)
have := fileList(haveList(s, protocol.LocalDeviceID))
sort.Sort(have)
if fmt.Sprint(have) != fmt.Sprint(localHave) {
t.Errorf("Have incorrect before invalidation;\n A: %v !=\n E: %v", have, localHave)
}
localHave[1] = protocol.FileInfo{Name: "b", Version: protocol.Vector{Counters: []protocol.Counter{{ID: myID, Value: 1001}}}, Invalid: true}
s.Update(protocol.LocalDeviceID, localHave[1:2])
have = fileList(haveList(s, protocol.LocalDeviceID))
sort.Sort(have)
if fmt.Sprint(have) != fmt.Sprint(localHave) {
t.Errorf("Have incorrect after invalidation;\n A: %v !=\n E: %v", have, localHave)
}
}
示例10: main
func main() {
srv := &clonesrv_t{
port: 5556,
kvmap: make(map[string]*kvmsg.Kvmsg),
}
// Set up our clone server sockets
srv.snapshot, _ = zmq.NewSocket(zmq.ROUTER)
srv.snapshot.Bind(fmt.Sprint("tcp://*:", srv.port))
srv.publisher, _ = zmq.NewSocket(zmq.PUB)
srv.publisher.Bind(fmt.Sprint("tcp://*:", srv.port+1))
srv.collector, _ = zmq.NewSocket(zmq.PULL)
srv.collector.Bind(fmt.Sprint("tcp://*:", srv.port+2))
// Register our handlers with reactor
reactor := zmq.NewReactor()
reactor.AddSocket(srv.snapshot, zmq.POLLIN,
func(e zmq.State) error { return snapshots(srv) })
reactor.AddSocket(srv.collector, zmq.POLLIN,
func(e zmq.State) error { return collector(srv) })
reactor.AddChannelTime(time.Tick(1000*time.Millisecond), 1,
func(v interface{}) error { return flush_ttl(srv) })
log.Println(reactor.Run(100 * time.Millisecond)) // precision: .1 seconds
}
示例11: zeroConst
// zeroConst returns a new "zero" constant of the specified type,
// which must not be an array or struct type: the zero values of
// aggregates are well-defined but cannot be represented by Const.
//
func zeroConst(t types.Type) *Const {
switch t := t.(type) {
case *types.Basic:
switch {
case t.Info()&types.IsBoolean != 0:
return NewConst(exact.MakeBool(false), t)
case t.Info()&types.IsNumeric != 0:
return NewConst(exact.MakeInt64(0), t)
case t.Info()&types.IsString != 0:
return NewConst(exact.MakeString(""), t)
case t.Kind() == types.UnsafePointer:
fallthrough
case t.Kind() == types.UntypedNil:
return nilConst(t)
default:
panic(fmt.Sprint("zeroConst for unexpected type:", t))
}
case *types.Pointer, *types.Slice, *types.Interface, *types.Chan, *types.Map, *types.Signature:
return nilConst(t)
case *types.Named:
return NewConst(zeroConst(t.Underlying()).Value, t)
case *types.Array, *types.Struct, *types.Tuple:
panic(fmt.Sprint("zeroConst applied to aggregate:", t))
}
panic(fmt.Sprint("zeroConst: unexpected ", t))
}
示例12: init
// Test of aliasing.
func init() {
type S struct {
a, b string
}
s1 := []string{"foo", "bar"}
s2 := s1 // creates an alias
s2[0] = "wiz"
if x := fmt.Sprint(s1, s2); x != "[wiz bar] [wiz bar]" {
panic(x)
}
pa1 := &[2]string{"foo", "bar"}
pa2 := pa1 // creates an alias
(*pa2)[0] = "wiz" // * required to workaround typechecker bug
if x := fmt.Sprint(*pa1, *pa2); x != "[wiz bar] [wiz bar]" {
panic(x)
}
a1 := [2]string{"foo", "bar"}
a2 := a1 // creates a copy
a2[0] = "wiz"
if x := fmt.Sprint(a1, a2); x != "[foo bar] [wiz bar]" {
panic(x)
}
t1 := S{"foo", "bar"}
t2 := t1 // copy
t2.a = "wiz"
if x := fmt.Sprint(t1, t2); x != "{foo bar} {wiz bar}" {
panic(x)
}
}
示例13: spinner
func spinner(waitMsg string, position int, channelEnd *ChannelEnd, wg *sync.WaitGroup) {
if channelEnd.closed {
wg.Done()
return
}
wg.Add(1)
chars := []string{".", "-", ".", "-", "-", ".", "-", ".", "-", "-", ".", "-", ".", "-", "-", "."}
if position > len(chars)-1 {
position = 0
}
postfix := ""
prefix := ""
for counter, str := range chars {
if counter < position {
postfix = fmt.Sprint(postfix, str)
} else {
prefix = fmt.Sprint(prefix, str)
}
}
clean()
switch runtime.GOOS {
case "windows":
prefix = "..."
postfix = ""
}
printWait(fmt.Sprintf("%s %s%s", waitMsg, prefix, postfix))
time.Sleep(100 * time.Millisecond)
spinner(waitMsg, position+1, channelEnd, wg)
wg.Done()
}
示例14: Run
func (c *help) Run(context *Context, client *Client) error {
const deprecatedMsg = "WARNING: %q is deprecated. Showing help for %q instead.\n\n"
output := fmt.Sprintf("%s version %s.\n\n", c.manager.name, c.manager.version)
if c.manager.wrong {
output += fmt.Sprint("ERROR: wrong number of arguments.\n\n")
}
if len(context.Args) > 0 {
if cmd, ok := c.manager.Commands[context.Args[0]]; ok {
if deprecated, ok := cmd.(*DeprecatedCommand); ok {
fmt.Fprintf(context.Stderr, deprecatedMsg, deprecated.oldName, cmd.Info().Name)
}
info := cmd.Info()
output += fmt.Sprintf("Usage: %s %s\n", c.manager.name, info.Usage)
output += fmt.Sprintf("\n%s\n", info.Desc)
flags := c.parseFlags(cmd)
if flags != "" {
output += fmt.Sprintf("\n%s", flags)
}
if info.MinArgs > 0 {
output += fmt.Sprintf("\nMinimum # of arguments: %d", info.MinArgs)
}
if info.MaxArgs > 0 {
output += fmt.Sprintf("\nMaximum # of arguments: %d", info.MaxArgs)
}
output += fmt.Sprint("\n")
} else if topic, ok := c.manager.topics[context.Args[0]]; ok {
output += topic
} else {
return fmt.Errorf("command %q does not exist.", context.Args[0])
}
} else {
output += fmt.Sprintf("Usage: %s %s\n\nAvailable commands:\n", c.manager.name, c.Info().Usage)
var commands []string
for name, cmd := range c.manager.Commands {
if _, ok := cmd.(*DeprecatedCommand); !ok {
commands = append(commands, name)
}
}
sort.Strings(commands)
for _, command := range commands {
description := c.manager.Commands[command].Info().Desc
description = strings.Split(description, "\n")[0]
description = strings.Split(description, ".")[0]
if len(description) > 2 {
description = strings.ToUpper(description[:1]) + description[1:]
}
output += fmt.Sprintf(" %-20s %s\n", command, description)
}
output += fmt.Sprintf("\nUse %s help <commandname> to get more information about a command.\n", c.manager.name)
if len(c.manager.topics) > 0 {
output += fmt.Sprintln("\nAvailable topics:")
for topic := range c.manager.topics {
output += fmt.Sprintf(" %s\n", topic)
}
output += fmt.Sprintf("\nUse %s help <topicname> to get more information about a topic.\n", c.manager.name)
}
}
io.WriteString(context.Stdout, output)
return nil
}
示例15: UpdateByUID
func UpdateByUID(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/json")
var col, uid, doc string
if !Require(w, r, "col", &col) {
return
}
if !Require(w, r, "uid", &uid) {
return
}
if !Require(w, r, "doc", &doc) {
return
}
V3Sync.RLock()
defer V3Sync.RUnlock()
dbcol := V3DB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
var newDoc interface{}
if err := json.Unmarshal([]byte(doc), &newDoc); err != nil {
http.Error(w, fmt.Sprintf("'%v' is not valid JSON document.", newDoc), 400)
return
}
newID, err := dbcol.UpdateByUID(uid, newDoc)
if err != nil {
http.Error(w, fmt.Sprint(err), 500)
return
}
w.Write([]byte(fmt.Sprint(newID)))
}