func main() { newlist := strconv.AppendQuote(make([]byte, 0), "") fmt.Println(string(newlist)) newlist = strconv.AppendQuote(make([]byte, 0), "abc") fmt.Println(string(newlist)) newlist = strconv.AppendQuote(make([]byte, 0), "中文") fmt.Println(string(newlist)) newlist = strconv.AppendQuote(make([]byte, 0), " ") // \t fmt.Println(string(newlist)) }
// Add data in the following format: // [dataId name="value" name2="value2"][dataId2 name="value"]. func addData(b []byte, data map[string]map[string]string) []byte { if len(data) == 0 { b = append(b, nilValueByte) return b } for _, dataID := range getSortedMapMapKeys(data) { params := data[dataID] b = append(b, dataStart) b = append(b, dataID...) // Add name and value in the following format: ` name="value"` for _, name := range getSortedMapKeys(params) { value := params[name] b = append(b, spaceByte) b = append(b, name...) b = append(b, equalByte) b = strconv.AppendQuote(b, value) } b = append(b, dataEnd) } return b }
func ExampleAppendQuote() { b := []byte("quote:") b = strconv.AppendQuote(b, `"Fran & Freddie's Diner"`) fmt.Println(string(b)) // Output: // quote:"\"Fran & Freddie's Diner\"" }
func (a *App) WriteAccessLog(req *Req, dur time.Duration) { if a.accessLog == nil { return } logEvery, _ := a.Cfg.GetInt("gop", "access_log_every", 0) if logEvery > 0 { a.suppressedAccessLogLines++ if a.suppressedAccessLogLines < logEvery { a.Debug("Suppressing access log line [%d/%d]", a.suppressedAccessLogLines, logEvery) return } } a.suppressedAccessLogLines = 0 // Copy an nginx-log access log /* --- gaiadev.leedsdev.net 0.022 192.168.111.1 - - [05/Feb/2014:13:39:22 +0000] "GET /bby/sso/login?next_url=https%3A%2F%2Fgaiadev.leedsdev.net%2F HTTP/1.1" 302 0 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:26.0) Gecko/20100101 Firefox/26.0" --- */ trimPort := func(s string) string { colonOffset := strings.IndexByte(s, ':') if colonOffset >= 0 { s = s[:colonOffset] } return s } quote := func(s string) string { return string(strconv.AppendQuote([]byte{}, s)) } reqFirstLine := fmt.Sprintf("%s %s %s", req.R.Method, req.R.RequestURI, req.R.Proto) referrerLine := req.R.Referer() if referrerLine == "" { referrerLine = "-" } uaLine := req.R.Header.Get("User-Agent") if uaLine == "" { uaLine = "-" } hostname := a.Hostname() logLine := fmt.Sprintf("%s %.3f %s %s %s %s %s %d %d %s %s\n", hostname, dur.Seconds(), trimPort(req.RealRemoteIP), "-", // Ident <giggle> "-", // user // req.startTime.Format("[02/Jan/2006:15:04:05 -0700]"), req.startTime.Format("["+time.RFC3339+"]"), quote(reqFirstLine), req.W.code, req.W.size, quote(referrerLine), quote(uaLine)) _, err := req.app.accessLog.WriteString(logLine) if err != nil { a.Errorf("Failed to write to access log: %s", err.Error()) } }
func AppendTest() { //Append 系列函数将整数等转换为字符串后,添加到现有的字节数组中。 str := make([]byte, 0, 100) str = strconv.AppendInt(str, 4567, 10) str = strconv.AppendBool(str, false) str = strconv.AppendQuote(str, "abcdefg") str = strconv.AppendQuoteRune(str, '单') fmt.Println(string(str)) }
func main() { /* /Enter the Key to be Written /writtenKey : String */ writtenKey := inputData() fmt.Println("Input Key : ", writtenKey) /* /Enter the data to be Written /writtenData : String */ writtenData := inputData() fmt.Println("Input data : ", writtenData) /* /Search or Write of the Start Key /dbKey : []byte */ var dbKey []byte /* /DATABASE Open */ db := dbOpen() /* /Convert Key from String to []byte */ dbKey = strconv.AppendQuote(dbKey, writtenKey) fmt.Println("dbKey is ", string(dbKey)) /* /DATABASE Put */ err := dbPut(db, writtenData, dbKey) if err != 0 { fmt.Println("DB Put ERROR") } /* /DATABASE All Read */ dbAllRead(db, dbKey) //fmt.Println("key : ", string(dbKey)) //fmt.Println("data : ", string(dbData)) /* /DATABASE Close */ defer db.Close() }
// keys returns the keys that associate a trid with a tag. func keys(trid string, tag string) (tridKey, tagKey []byte) { quoted := strconv.AppendQuote(nil, tag) tridKey = make([]byte, len(trid)+len(quoted)) copy(tridKey, trid) copy(tridKey[len(trid):], quoted) tagKey = make([]byte, len(quoted)+len(trid)) copy(tagKey, quoted) copy(tagKey[len(quoted):], trid) return tridKey, tagKey }
// fmt_q formats a string as a double-quoted, escaped Go string constant. // If f.sharp is set a raw (backquoted) string may be returned instead // if the string does not contain any control characters other than tab. func (f *fmt) fmt_q(s string) { s = f.truncate(s) if f.sharp && strconv.CanBackquote(s) { f.padString("`" + s + "`") return } buf := f.intbuf[:0] if f.plus { f.pad(strconv.AppendQuoteToASCII(buf, s)) } else { f.pad(strconv.AppendQuote(buf, s)) } }
func Teststrings() { //字符串s中是否包含substr,返回bool值 fmt.Println(strings.Contains("seafood", "foo")) fmt.Println(strings.Contains("seafood", "bar")) fmt.Println(strings.Contains("seafood", "")) fmt.Println(strings.Contains("", "")) s := []string{"foo", "bar", "baz"} //字符串链接,把slice a通过sep链接起来 fmt.Println(strings.Join(s, ", ")) //在字符串s中查找sep所在的位置,返回位置值,找不到返回-1 fmt.Println(strings.Index("chicken", "ken")) fmt.Println(strings.Index("chicken", "dmr")) //重复s字符串count次,最后返回重复的字符串 fmt.Println("ba" + strings.Repeat("na", 2)) //在s字符串中,把old字符串替换为new字符串,n表示替换的次数,小于0表示全部替换 fmt.Println(strings.Replace("oink oink oink", "k", "ky", 2)) fmt.Println(strings.Replace("oink oink oink", "oink", "moo", -1)) //把s字符串按照sep分割,返回slice fmt.Printf("%q\n", strings.Split("a,b,c", ",")) fmt.Printf("%q\n", strings.Split("a man a plan a canal panama", "a ")) fmt.Printf("%q\n", strings.Split(" xyz ", "")) fmt.Printf("%q\n", strings.Split("", "Bernardo O'Higgins")) //在s字符串中去除cutset指定的字符串 fmt.Printf("[%q]\n", strings.Trim(" !!! Achtung !!! ", "! ")) //去除s字符串的空格符,并且按照空格分割返回slice fmt.Printf("Fields are: %q\n", strings.Fields(" foo bar baz ")) //Append 系列函数将整数等转换为字符串后,添加到现有的字节数组中。 str := make([]byte, 0, 100) str = strconv.AppendInt(str, 4567, 10) str = strconv.AppendBool(str, false) str = strconv.AppendQuote(str, "abcdefg") str = strconv.AppendQuoteRune(str, '单') fmt.Println(string(str)) //Format 系列函数把其他类型的转换为字符串 a := strconv.FormatBool(false) b := strconv.FormatFloat(123.23, 'g', 12, 64) c := strconv.FormatInt(1234, 10) d := strconv.FormatUint(12345, 10) e := strconv.Itoa(1023) fmt.Println(a, b, c, d, e) }
func main() { str := make([]byte, 0, 100) str = strconv.AppendInt(str, 4567, 10) str = strconv.AppendBool(str, false) str = strconv.AppendQuote(str, "adcdef") str = strconv.AppendQuoteRune(str, '中') fmt.Println(string(str)) fl := strconv.FormatFloat(123.23, 'g', 12, 64) fmt.Println(fl) ui, err := strconv.ParseUint("12345", 10, 64) if err != nil { fmt.Println(err) } fmt.Println(ui + 10) }
func getTrids(tag string) ([]string, error) { quoted := strconv.AppendQuote(nil, tag) trids := []string{} err := db.View(func(tx *bolt.Tx) error { b := tx.Bucket(tag2trid) c := b.Cursor() for k, _ := c.Seek(quoted); k != nil; k, _ = c.Next() { if !bytes.HasPrefix(k, quoted) { break } trids = append(trids, string(k[len(quoted):])) } return nil }) return trids, err }
func main() { for _, truth := range []string{"1", "t", "TRUE", "false", "F", "0", "5"} { if b, err := strconv.ParseBool(truth); err != nil { fmt.Printf("\n%v", err) } else { fmt.Print(b, " ") } } fmt.Println() x, err := strconv.ParseFloat("-99.7", 64) fmt.Printf("%8T %6v %v\n", x, x, err) y, err := strconv.ParseInt("71309", 10, 16) fmt.Printf("%8T %6v %v\n", y, y, err) z, err := strconv.Atoi("71309") fmt.Printf("%8T %6v %v\n", z, z, err) fmt.Println() s := strconv.FormatBool(z > 100) fmt.Println(s) i, err := strconv.ParseInt("0xDEED", 0, 32) fmt.Println(i, err) j, err := strconv.ParseInt("0707", 0, 32) fmt.Println(j, err) k, err := strconv.ParseInt("10111010001", 2, 32) fmt.Println(k, err) m := 16769023 fmt.Println(strconv.Itoa(m)) fmt.Println(strconv.FormatInt(int64(m), 10)) fmt.Println(strconv.FormatInt(int64(m), 2)) fmt.Println(strconv.FormatInt(int64(m), 16)) fmt.Println() s = "Alle ønsker å være fri." quoted := strconv.QuoteToASCII(s) fmt.Println(quoted) fmt.Println(strconv.Unquote(quoted)) var bs []byte bs = strconv.AppendQuote(bs, "👍") fmt.Printf("|%s|% #x|%d|\n", string(bs), bs, bs) }
func (c *C) logMultiLine(s string) { b := make([]byte, 0, len(s)*2) i := 0 n := len(s) for i < n { j := i + 1 for j < n && s[j-1] != '\n' { j++ } b = append(b, "... "...) b = strconv.AppendQuote(b, s[i:j]) if j < n { b = append(b, " +"...) } b = append(b, '\n') i = j } c.writeLog(b) }
func processString() { str := make([]byte, 0, 100) // str := "" fmt.Println(str) str = strconv.AppendInt(str, 4567, 10) str = strconv.AppendBool(str, false) str = strconv.AppendQuote(str, "abcde") str = strconv.AppendQuoteRune(str, '周') fmt.Println(str) fmt.Println(string(str)) str1 := strconv.FormatBool(false) fmt.Println(str1) str1 = strings.Repeat(str1, 2) fmt.Println(str1) fmt.Println(strings.Contains(str1, "al")) fmt.Println(strings.Index(str1, "al")) fmt.Println(strings.Trim("!a james May !a", "!a")) }
func main() { // Append , 转换并添加到现有字符串 str := make([]byte, 0, 1000) str = strconv.AppendInt(str, 4567, 10) str = strconv.AppendBool(str, false) str = strconv.AppendQuote(str, "abcdefg") str = strconv.AppendQuoteRune(str, '单') fmt.Println(string(str)) // Format 把其他类型转成字符串 a := strconv.FormatBool(false) b := strconv.FormatFloat(123.23, 'g', 12, 64) c := strconv.FormatInt(1234, 10) d := strconv.FormatUint(12345, 10) e := strconv.Itoa(1023) fmt.Println(a, b, c, d, e) // Parse 把字符串转为其他类型 a1, err := strconv.ParseBool("false") if err != nil { fmt.Println(err) } else { fmt.Println(a1) } b1, err := strconv.ParseFloat("123.23", 64) c1, err := strconv.ParseInt("1234", 10, 64) d1, err := strconv.ParseUint("12345", 10, 64) fmt.Println(a1, b1, c1, d1) }
func prettyPrint(w *WorldDat, v reflect.Value, buf, indent []byte, outerTag reflect.StructTag) []byte { bufPreType := buf buf = append(buf, v.Kind().String()...) buf = append(buf, ' ') if v.Type().String() != v.Kind().String() { buf = append(buf, v.Type().String()...) buf = append(buf, ' ') } if p, ok := v.Interface().(prettyPrinter); ok { return p.prettyPrint(w, buf, indent, outerTag) } switch v.Kind() { case reflect.Ptr: if v.IsNil() { buf = append(buf, "(nil)"...) } else { buf = append(bufPreType, '&') buf = prettyPrint(w, v.Elem(), buf, indent, outerTag) } case reflect.Struct: buf = append(buf, '{') indent = append(indent, '\t') for i, l := 0, v.NumField(); i < l; i++ { fieldTag := v.Type().Field(i).Tag if tag := fieldTag.Get("df2014_version_min"); tag != "" { expected, err := strconv.ParseUint(tag, 0, 32) if err != nil { panic(err) } if w.Version < versions.Version(expected) { continue } } if tag := fieldTag.Get("df2014_version_max"); tag != "" { expected, err := strconv.ParseUint(tag, 0, 32) if err != nil { panic(err) } if w.Version > versions.Version(expected) { continue } } if tag := fieldTag.Get("df2014_type"); tag != "" { expected, err := strconv.ParseInt(tag, 0, 64) if err != nil { panic(err) } if v.FieldByName("Type").Int() != expected { continue } } buf = append(buf, indent...) buf = append(buf, v.Type().Field(i).Name...) buf = append(buf, ": "...) buf = prettyPrint(w, v.Field(i), buf, indent, fieldTag) } buf = append(buf, indent[:len(indent)-1]...) buf = append(buf, '}') case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: buf = strconv.AppendInt(buf, v.Int(), 10) buf = append(buf, " (0x"...) buf = strconv.AppendUint(buf, uint64(v.Int())&(1<<uint(v.Type().Bits())-1), 16) buf = append(buf, ')') case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: buf = strconv.AppendUint(buf, v.Uint(), 10) buf = append(buf, " (0x"...) buf = strconv.AppendUint(buf, v.Uint(), 16) buf = append(buf, ')') case reflect.String: buf = append(buf, "(len = "...) buf = strconv.AppendInt(buf, int64(len([]rune(v.String()))), 10) buf = append(buf, ") "...) buf = strconv.AppendQuote(buf, v.String()) case reflect.Bool: buf = strconv.AppendBool(buf, v.Bool()) case reflect.Slice, reflect.Array: if v.Kind() == reflect.Slice { buf = append(buf, "(len = "...) buf = strconv.AppendInt(buf, int64(v.Len()), 10) buf = append(buf, ") {"...) } else { buf = append(buf, '{') } indent = append(indent, '\t') var names []string if tag := outerTag.Get("df2014_key_is_string"); tag != "" { names = reflect.ValueOf(w.StringTables).FieldByName(tag).Interface().([]string) } for i, l := 0, v.Len(); i < l; i++ { buf = append(buf, indent...) buf = strconv.AppendInt(buf, int64(i), 10) if i >= 0 && int(i) < len(names) { buf = append(buf, " ("...) buf = append(buf, names[i]...) buf = append(buf, ')') } buf = append(buf, ": "...) buf = prettyPrint(w, v.Index(i), buf, indent, "") } buf = append(buf, indent[:len(indent)-1]...) buf = append(buf, '}') case reflect.Map: buf = append(buf, "(len = "...) buf = strconv.AppendInt(buf, int64(v.Len()), 10) buf = append(buf, ") {"...) indent = append(indent, '\t') var elements mapElements keys := v.MapKeys() for _, key := range keys { elements = append(elements, mapElement{key: key, value: v.MapIndex(key)}) } sort.Sort(elements) for _, e := range elements { buf = append(buf, indent...) buf = prettyPrint(w, e.key, buf, indent, "") buf = append(buf, ": "...) buf = prettyPrint(w, e.value, buf, indent, "") } buf = append(buf, indent[:len(indent)-1]...) buf = append(buf, '}') default: panic("unhandled type: " + v.Kind().String() + " " + v.Type().String()) } return buf }
func (par *stringParser) WriteValue(out io.Writer, valueOf reflect.Value) error { _, err := out.Write(strconv.AppendQuote(nil, valueOf.String())) return err }
func main() { // Go offers several printing "verbs" designed to // format general Go values. For example, this prints // an instance of our `point` struct. p := point{1, 2} fmt.Printf("%v\n", p) // If the value is a struct, the `%+v` variant will // include the struct's field names. fmt.Printf("%+v\n", p) // The `%#v` variant prints a Go syntax representation // of the value, i.e. the source code snippet that // would produce that value. fmt.Printf("%#v\n", p) // To print the type of a value, use `%T`. fmt.Printf("%T\n", p) // Formatting booleans is straight-forward. fmt.Printf("%t\n", true) // There are many options for formatting integers. // Use `%d` for standard, base-10 formatting. fmt.Printf("%d\n", 123) // This prints a binary representation. fmt.Printf("%b\n", 14) // This prints the character corresponding to the // given integer. fmt.Printf("%c\n", 33) // `%x` provides hex encoding. fmt.Printf("%x\n", 456) // There are also several formatting options for // floats. For basic decimal formatting use `%f`. fmt.Printf("%f\n", 78.9) // `%e` and `%E` format the float in (slightly // different versions of) scientific notation. fmt.Printf("%e\n", 123400000.0) fmt.Printf("%E\n", 123400000.0) // For basic string printing use `%s`. fmt.Printf("%s\n", "\"string\"") // To double-quote strings as in Go source, use `%q`. fmt.Printf("%q\n", "\"string\"") // As with integers seen earlier, `%x` renders // the string in base-16, with two output characters // per byte of input. fmt.Printf("%x\n", "hex this") // To print a representation of a pointer, use `%p`. fmt.Printf("%p\n", &p) // When formatting numbers you will often want to // control the width and precision of the resulting // figure. To specify the width of an integer, use a // number after the `%` in the verb. By default the // result will be right-justified and padded with // spaces. fmt.Printf("|%6d|%6d|\n", 12, 345) // You can also specify the width of printed floats, // though usually you'll also want to restrict the // decimal precision at the same time with the // width.precision syntax. fmt.Printf("|%6.2f|%6.2f|\n", 1.2, 3.45) // To left-justify, use the `-` flag. fmt.Printf("|%-6.2f|%-6.2f|\n", 1.2, 3.45) // You may also want to control width when formatting // strings, especially to ensure that they align in // table-like output. For basic right-justified width. fmt.Printf("|%6s|%6s|\n", "foo", "b") // To left-justify use the `-` flag as with numbers. fmt.Printf("|%-6s|%-6s|\n", "foo", "b") // So far we've seen `Printf`, which prints the // formatted string to `os.Stdout`. `Sprintf` formats // and returns a string without printing it anywhere. s := fmt.Sprintf("a %s", "string") fmt.Println(s) // You can format+print to `io.Writers` other than // `os.Stdout` using `Fprintf`. fmt.Fprintf(os.Stderr, "an %s\n", "error") bs := []byte{} str := "this is a test!" c := len(str) bs = strconv.AppendInt(bs, int64(c), 10) bs = strconv.AppendQuote(bs, str) bs = strconv.AppendInt(bs, 123, 10) bs = strconv.AppendBool(bs, true) bs = strconv.AppendFloat(bs, 1.23, 'f', -1, 64) fmt.Println("string:", string(bs), " len:", len(bs)) fmt.Println("bool: ", strconv.FormatBool(true)) fmt.Println("2 int: ", strconv.FormatInt(123, 10)) fmt.Println("36 int: ", strconv.FormatInt(123, 2)) fmt.Println("2 uint: ", strconv.FormatUint(123, 10)) fmt.Println("36 uint: ", strconv.FormatUint(123, 2)) fmt.Println("float b: ", strconv.FormatFloat(1.230, 'b', -1, 64)) fmt.Println("float E: ", strconv.FormatFloat(1.230, 'E', -1, 64)) fmt.Println("float e: ", strconv.FormatFloat(1.230, 'e', -1, 64)) fmt.Println("float f: ", strconv.FormatFloat(1.2301231, 'f', 6, 64)) fmt.Println("float G: ", strconv.FormatFloat(1.23012321, 'G', 6, 64)) fmt.Println("float g: ", strconv.FormatFloat(1.230123213, 'g', 6, 64)) reader := strings.NewReader(str) b, _ := reader.ReadByte() fmt.Println(strconv.Atoi(string(b))) }
func (bs Bytes) AppendQuote(s string) Bytes { r := strconv.AppendQuote([]byte(bs), s) return Bytes(r) }
func quoteString(v interface{}) string { b := []byte{} b = strconv.AppendQuote(b, fmt.Sprintf("%v", v)) return string(b) }
func formatDataKey(buf []byte, k []byte) ([]byte, error) { if len(k) < 2 { return nil, errInvalidBinLogEvent } buf = append(buf, fmt.Sprintf("DB:%2d ", k[0])...) buf = append(buf, fmt.Sprintf("%s ", TypeName[k[1]])...) db := new(DB) db.index = k[0] //to do format at respective place switch k[1] { case KVType: if key, err := db.decodeKVKey(k); err != nil { return nil, err } else { buf = strconv.AppendQuote(buf, String(key)) } case HashType: if key, field, err := db.hDecodeHashKey(k); err != nil { return nil, err } else { buf = strconv.AppendQuote(buf, String(key)) buf = append(buf, ' ') buf = strconv.AppendQuote(buf, String(field)) } case HSizeType: if key, err := db.hDecodeSizeKey(k); err != nil { return nil, err } else { buf = strconv.AppendQuote(buf, String(key)) } case ListType: if key, seq, err := db.lDecodeListKey(k); err != nil { return nil, err } else { buf = strconv.AppendQuote(buf, String(key)) buf = append(buf, ' ') buf = strconv.AppendInt(buf, int64(seq), 10) } case LMetaType: if key, err := db.lDecodeMetaKey(k); err != nil { return nil, err } else { buf = strconv.AppendQuote(buf, String(key)) } case ZSetType: if key, m, err := db.zDecodeSetKey(k); err != nil { return nil, err } else { buf = strconv.AppendQuote(buf, String(key)) buf = append(buf, ' ') buf = strconv.AppendQuote(buf, String(m)) } case ZSizeType: if key, err := db.zDecodeSizeKey(k); err != nil { return nil, err } else { buf = strconv.AppendQuote(buf, String(key)) } case ZScoreType: if key, m, score, err := db.zDecodeScoreKey(k); err != nil { return nil, err } else { buf = strconv.AppendQuote(buf, String(key)) buf = append(buf, ' ') buf = strconv.AppendQuote(buf, String(m)) buf = append(buf, ' ') buf = strconv.AppendInt(buf, score, 10) } case BitType: if key, seq, err := db.bDecodeBinKey(k); err != nil { return nil, err } else { buf = strconv.AppendQuote(buf, String(key)) buf = append(buf, ' ') buf = strconv.AppendUint(buf, uint64(seq), 10) } case BitMetaType: if key, err := db.bDecodeMetaKey(k); err != nil { return nil, err } else { buf = strconv.AppendQuote(buf, String(key)) } case ExpTimeType: if tp, key, t, err := db.expDecodeTimeKey(k); err != nil { return nil, err } else { buf = append(buf, TypeName[tp]...) buf = append(buf, ' ') buf = strconv.AppendQuote(buf, String(key)) buf = append(buf, ' ') buf = strconv.AppendInt(buf, t, 10) } case ExpMetaType: if tp, key, err := db.expDecodeMetaKey(k); err != nil { return nil, err } else { buf = append(buf, TypeName[tp]...) buf = append(buf, ' ') buf = strconv.AppendQuote(buf, String(key)) } default: return nil, errInvalidBinLogEvent } return buf, nil }
func encodeString(buf []byte, s string) []byte { return strconv.AppendQuote(buf, s) }
// WriteStringValues always writes quoted strings to the buffer func (b *recordBuffer) WriteStringValues(s ...string) { var t []byte t = strconv.AppendQuote(t, strings.Join(s, ` `)) _, _ = b.Write(t) b.writeSpace() }
func (b *buffer) appendQuote(s string) { b.buf = strconv.AppendQuote(b.buf, s) }