本文整理汇总了Golang中strconv.Itoa函数的典型用法代码示例。如果您正苦于以下问题:Golang Itoa函数的具体用法?Golang Itoa怎么用?Golang Itoa使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Itoa函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: getUpdates
func getUpdates(token string, offset int, timeout int) (updates []Update, err error) {
params := url.Values{}
params.Set("offset", strconv.Itoa(offset))
params.Set("timeout", strconv.Itoa(timeout))
updatesJSON, err := sendCommand("getUpdates", token, params)
if err != nil {
return
}
var updatesRecieved struct {
Ok bool
Result []Update
Description string
}
err = json.Unmarshal(updatesJSON, &updatesRecieved)
if err != nil {
return
}
if !updatesRecieved.Ok {
err = FetchError{updatesRecieved.Description}
return
}
updates = updatesRecieved.Result
return
}
示例2: Values
func (plan *Plan) Values(values *url.Values) error {
if plan == nil {
// TODO: Throw error
}
if plan.ID == "" {
// TODO: Throw error
}
if plan.Name == "" {
// TODO: Throw error
}
if plan.Amount <= 0 {
// TODO: Throw error
}
if plan.Currency != "USD" {
// TODO: Throw error
}
if plan.Interval != "month" && plan.Interval != "year" {
// TODO: Throw error
}
if plan.TrialDays > 0 {
values.Set("trial_period_days", strconv.Itoa(plan.TrialDays))
}
values.Set("id", plan.ID)
values.Set("amount", strconv.Itoa(plan.Amount))
values.Set("currency", plan.Currency)
values.Set("interval", plan.Interval)
values.Set("name", plan.Name)
return nil
}
示例3: TestManyFailures
func TestManyFailures(t *testing.T) {
fmt.Printf("Test: One ManyFailures mapreduce ...\n")
mr := setup()
i := 0
done := false
for !done {
select {
case done = <-mr.DoneChannel:
check(t, mr.file)
cleanup(mr)
break
default:
// Start 2 workers each sec. The workers fail after 10 jobs
w := port("worker" + strconv.Itoa(i))
go RunWorker(mr.MasterAddress, w, MapFunc, ReduceFunc, 10)
i++
w = port("worker" + strconv.Itoa(i))
go RunWorker(mr.MasterAddress, w, MapFunc, ReduceFunc, 10)
i++
time.Sleep(1 * time.Second)
}
}
fmt.Printf(" ... Many Failures Passed\n")
}
示例4: TestUnreliableOneKey
func TestUnreliableOneKey(t *testing.T) {
const nservers = 3
cfg := make_config(t, "onekey", nservers, true, -1)
defer cfg.cleanup()
ck := cfg.makeClient(cfg.All())
fmt.Printf("Test: Concurrent Append to same key, unreliable ...\n")
ck.Put("k", "")
const nclient = 5
const upto = 10
spawn_clients_and_wait(t, cfg, nclient, func(me int, myck *Clerk, t *testing.T) {
n := 0
for n < upto {
myck.Append("k", "x "+strconv.Itoa(me)+" "+strconv.Itoa(n)+" y")
n++
}
})
var counts []int
for i := 0; i < nclient; i++ {
counts = append(counts, upto)
}
vx := ck.Get("k")
checkConcurrentAppends(t, vx, counts)
fmt.Printf(" ... Passed\n")
}
示例5: initRand
// Initialize entities to random variables in order to test ledger status consensus
func (t *SimpleChaincode) initRand(stub *shim.ChaincodeStub, args []string) ([]byte, error) {
var A, B string // Entities
var Aval, Bval int // Asset holdings
var err error
if len(args) != 4 {
return nil, errors.New("Incorrect number of arguments. Expecting 4")
}
// Initialize the chaincode
A = args[0]
Aval = rand.Intn(100)
B = args[1]
Bval = rand.Intn(100)
fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)
// Write the state to the ledger
err = stub.PutState(A, []byte(strconv.Itoa(Aval)))
if err != nil {
return nil, err
}
err = stub.PutState(B, []byte(strconv.Itoa(Bval)))
if err != nil {
return nil, err
}
return nil, nil
}
示例6: TestWatcherTimeout
func TestWatcherTimeout(t *testing.T) {
server, etcdStorage := newEtcdTestStorage(t, testapi.Default.Codec(), etcdtest.PathPrefix())
defer server.Terminate(t)
cacher := newTestCacher(etcdStorage)
defer cacher.Stop()
// initialVersion is used to initate the watcher at the beginning of the world,
// which is not defined precisely in etcd.
initialVersion, err := cacher.LastSyncResourceVersion()
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
startVersion := strconv.Itoa(int(initialVersion))
// Create a watcher that will not be reading any result.
watcher, err := cacher.WatchList(context.TODO(), "pods/ns", startVersion, storage.Everything)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
defer watcher.Stop()
// Create a second watcher that will be reading result.
readingWatcher, err := cacher.WatchList(context.TODO(), "pods/ns", startVersion, storage.Everything)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
defer readingWatcher.Stop()
for i := 1; i <= 22; i++ {
pod := makeTestPod(strconv.Itoa(i))
_ = updatePod(t, etcdStorage, pod, nil)
verifyWatchEvent(t, readingWatcher, watch.Added, pod)
}
}
示例7: FmtDateShort
// FmtDateShort returns the short date representation of 't' for 'it_IT'
func (it *it_IT) FmtDateShort(t time.Time) string {
b := make([]byte, 0, 32)
if t.Day() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Day()), 10)
b = append(b, []byte{0x2f}...)
if t.Month() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Month()), 10)
b = append(b, []byte{0x2f}...)
if t.Year() > 9 {
b = append(b, strconv.Itoa(t.Year())[2:]...)
} else {
b = append(b, strconv.Itoa(t.Year())[1:]...)
}
return string(b)
}
示例8: TestUpdate
func TestUpdate(t *testing.T) {
a, _ := NewHyperLogLog(0.05)
b, _ := NewHyperLogLog(0.05)
c, _ := NewHyperLogLog(0.05)
for i := 0; i < 2; i++ {
add := strconv.Itoa(i)
a.Add(add)
c.Add(add)
}
for i := 2; i < 4; i++ {
add := strconv.Itoa(i)
b.Add(add)
c.Add(add)
}
a.Update([]*HyperLogLog{b})
if hllEqual(a, b) {
t.Error("TestUpdate: a and b are equal")
}
if hllEqual(b, c) {
t.Error("TestUpdate: b and c are equal")
}
if !hllEqual(a, c) {
t.Error("TestUpdate: a and c are not equal")
}
d, _ := NewHyperLogLog(0.01)
err := a.Update([]*HyperLogLog{d})
if err == nil {
t.Error("TestUpdate: different precisions didn't throw an error")
}
}
示例9: toURLValues
func (p *ListDomainChildrenParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
if v, found := p.p["isrecursive"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("isrecursive", vv)
}
if v, found := p.p["keyword"]; found {
u.Set("keyword", v.(string))
}
if v, found := p.p["listall"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("listall", vv)
}
if v, found := p.p["name"]; found {
u.Set("name", v.(string))
}
if v, found := p.p["page"]; found {
vv := strconv.Itoa(v.(int))
u.Set("page", vv)
}
if v, found := p.p["pagesize"]; found {
vv := strconv.Itoa(v.(int))
u.Set("pagesize", vv)
}
return u
}
示例10: FindUserId
func FindUserId(name string) string {
var users map[string][]User_t
uri := "/api/1.0/workspaces/" + strconv.Itoa(config.Load().Workspace) + "/typeahead?type=user&query=" + name
err := json.Unmarshal(Get(uri, nil), &users)
utils.Check(err)
return strconv.Itoa(users["data"][0].Id)
}
示例11: HandleResponse
func (p *ReverseProxy) HandleResponse(rw http.ResponseWriter, res *http.Response, req *http.Request, ses *SessionState) error {
for _, h := range hopHeaders {
res.Header.Del(h)
}
defer res.Body.Close()
// Close connections
if config.CloseConnections {
res.Header.Set("Connection", "close")
}
// Add resource headers
if ses != nil {
// We have found a session, lets report back
res.Header.Add("X-RateLimit-Limit", strconv.Itoa(int(ses.QuotaMax)))
res.Header.Add("X-RateLimit-Remaining", strconv.Itoa(int(ses.QuotaRemaining)))
res.Header.Add("X-RateLimit-Reset", strconv.Itoa(int(ses.QuotaRenews)))
}
copyHeader(rw.Header(), res.Header)
rw.WriteHeader(res.StatusCode)
p.copyResponse(rw, res.Body)
return nil
}
示例12: getSTEvents
func getSTEvents(lastSeenID int) ([]Event, error) {
Trace.Println("Requesting STEvents: " + strconv.Itoa(lastSeenID))
r, err := http.NewRequest("GET", target+"/rest/events?since="+strconv.Itoa(lastSeenID), nil)
res, err := performRequest(r)
defer func() {
if res != nil && res.Body != nil {
res.Body.Close()
}
}()
if err != nil {
Warning.Println("Failed to perform request", err)
return nil, err
}
if res.StatusCode != 200 {
Warning.Printf("Status %d != 200 for GET", res.StatusCode)
return nil, errors.New("Invalid HTTP status code")
}
bs, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
var events []Event
err = json.Unmarshal(bs, &events)
return events, err
}
示例13: generateID
//generate a random id to represent the unique id
func generateID(adId int) string {
t := time.Now()
year, month, day := t.Date()
var id = Hex(4) + "-" + strconv.Itoa(year) +
strconv.Itoa(int(month)) + strconv.Itoa(day) + "-" + strconv.Itoa(adId)
return id
}
示例14: buildLogLine
// buildLogLine creates a common log format
// in addittion to the common fields, we also append referrer, user agent and request ID
func buildLogLine(l *responseLogger, r *http.Request, start time.Time) string {
username := parseUsername(r)
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
host = r.RemoteAddr
}
uri := r.URL.RequestURI()
referer := r.Referer()
userAgent := r.UserAgent()
fields := []string{
host,
"-",
detect(username, "-"),
fmt.Sprintf("[%s]", start.Format("02/Jan/2006:15:04:05 -0700")),
r.Method,
uri,
r.Proto,
detect(strconv.Itoa(l.Status()), "-"),
strconv.Itoa(l.Size()),
detect(referer, "-"),
detect(userAgent, "-"),
r.Header.Get("Request-Id"),
}
return strings.Join(fields, " ")
}
示例15: buildCommonLogLine
// buildCommonLogLine builds a log entry for req in Apache Common Log Format.
// ts is the timestamp with which the entry should be logged.
// status and size are used to provide the response HTTP status and size.
func buildCommonLogLine(req *http.Request, url url.URL, ts time.Time, status int, size int) []byte {
username := "-"
if url.User != nil {
if name := url.User.Username(); name != "" {
username = name
}
}
host, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
host = req.RemoteAddr
}
uri := url.RequestURI()
buf := make([]byte, 0, 3*(len(host)+len(username)+len(req.Method)+len(uri)+len(req.Proto)+50)/2)
buf = append(buf, host...)
buf = append(buf, " - "...)
buf = append(buf, username...)
buf = append(buf, " ["...)
buf = append(buf, ts.Format("02/Jan/2006:15:04:05 -0700")...)
buf = append(buf, `] "`...)
buf = append(buf, req.Method...)
buf = append(buf, " "...)
buf = appendQuoted(buf, uri)
buf = append(buf, " "...)
buf = append(buf, req.Proto...)
buf = append(buf, `" `...)
buf = append(buf, strconv.Itoa(status)...)
buf = append(buf, " "...)
buf = append(buf, strconv.Itoa(size)...)
return buf
}