本文整理汇总了Golang中strconv.FormatUint函数的典型用法代码示例。如果您正苦于以下问题:Golang FormatUint函数的具体用法?Golang FormatUint怎么用?Golang FormatUint使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了FormatUint函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestProvideModel
func TestProvideModel(t *testing.T) {
r := Resource{}
assertNoErr(db.Save(&r).Error)
router = gin.New()
router.GET("/r/:id", res.ProvideModel(func(c *gin.Context, s resources.DBModel) {
if s == nil {
t.Fatal("ProvideModel passed a nil DBModel")
}
c.String(200, "OK")
}))
tests := []struct {
Code int
ID string
}{
{200, strconv.FormatUint(uint64(r.ID), 10)},
// We only have one resource, so this shouldn't exist
{404, strconv.FormatUint(uint64(r.ID+1), 10)},
{404, "0"},
{404, "not-an-id"},
}
for _, test := range tests {
path := fmt.Sprintf("/r/%s", test.ID)
res := doRequest(t, "GET", path, nil)
if res.Code != test.Code {
t.Fatalf("Error finding resource at %s, expected %d, got %d: %v", path, test.Code, res.Code, res)
}
}
}
示例2: ExtractTar
// ExtractTar extracts a tarball (from a io.Reader) into the given directory
// if pwl is not nil, only the paths in the map are extracted.
// If overwrite is true, existing files will be overwritten.
// The extraction is executed by fork/exec()ing a new process. The new process
// needs the CAP_SYS_CHROOT capability.
func ExtractTar(rs io.Reader, dir string, overwrite bool, uidRange *user.UidRange, pwl PathWhitelistMap) error {
r, w, err := os.Pipe()
if err != nil {
return err
}
defer w.Close()
enc := json.NewEncoder(w)
cmd := mcEntrypoint.Cmd(dir, strconv.FormatBool(overwrite),
strconv.FormatUint(uint64(uidRange.Shift), 10),
strconv.FormatUint(uint64(uidRange.Count), 10))
cmd.ExtraFiles = []*os.File{r}
cmd.Stdin = rs
encodeCh := make(chan error)
go func() {
encodeCh <- enc.Encode(pwl)
}()
out, err := cmd.CombinedOutput()
// read from blocking encodeCh to release the goroutine
encodeErr := <-encodeCh
if err != nil {
return fmt.Errorf("extracttar error: %v, output: %s", err, out)
}
if encodeErr != nil {
return errwrap.Wrap(errors.New("extracttar failed to json encode filemap"), encodeErr)
}
return nil
}
示例3: programMangle
func programMangle(vni uint32, add bool) (err error) {
var (
p = strconv.FormatUint(uint64(vxlanPort), 10)
c = fmt.Sprintf("0>>22&[email protected]&0xFFFFFF00=%d", int(vni)<<8)
m = strconv.FormatUint(uint64(mark), 10)
chain = "OUTPUT"
rule = []string{"-p", "udp", "--dport", p, "-m", "u32", "--u32", c, "-j", "MARK", "--set-mark", m}
a = "-A"
action = "install"
)
if add == iptables.Exists(iptables.Mangle, chain, rule...) {
return
}
if !add {
a = "-D"
action = "remove"
}
if err = iptables.RawCombinedOutput(append([]string{"-t", string(iptables.Mangle), a, chain}, rule...)...); err != nil {
logrus.Warnf("could not %s mangle rule: %v", action, err)
}
return
}
示例4: PortPathsFor
func (p Port) PortPathsFor() (base string, path string) {
root := Device("1").DevicePath()
prefix := p / portsPerBlock
base = filepath.Join(root, strconv.FormatUint(uint64(prefix), 10))
path = filepath.Join(base, strconv.FormatUint(uint64(p), 10))
return
}
示例5: Insert
func (a *Auditor) Insert(r *RequestBundle, key, ip string, user User, from, to map[string]interface{}) error {
changes := []Change{}
for k, v := range to {
id, err := r.GetID()
if err != nil {
return err
}
change := Change{
ID: id,
Key: key,
From: from[k],
To: v,
Field: k,
Timestamp: time.Now(),
IP: ip,
User: user,
}
changes = append(changes, change)
}
reply := a.client.MultiCall(func(mc *redis.MultiCall) {
for _, change := range changes {
user_str := ""
if change.User.ID != 0 {
user_str = strconv.FormatUint(change.User.ID, 10)
}
mc.Hmset("audit:"+change.Key+":item:"+strconv.FormatUint(change.ID, 10), "from", change.From, "to", change.To, "field", change.Field, "timestamp", change.Timestamp.Format(time.RFC3339), "user", user_str)
mc.Lpush("audit:"+key, change.ID)
}
})
return reply.Err
}
示例6: monitor
func monitor() {
go logStatus()
if len(*flaghttp) == 0 {
return
}
go hub.run()
go httpHandler()
lastQueryCount := qCounter
for {
newQueries := qCounter - lastQueryCount
lastQueryCount = qCounter
status := map[string]string{}
status["up"] = strconv.Itoa(int(time.Since(timeStarted).Seconds()))
status["qs"] = strconv.FormatUint(qCounter, 10)
status["qps"] = strconv.FormatUint(newQueries, 10)
message, err := json.Marshal(status)
if err == nil {
hub.broadcast <- string(message)
}
time.Sleep(1 * time.Second)
}
}
示例7: makeGRPCContext
// encode metadata to context in grpc specific way
func (f *framework) makeGRPCContext(ctx context.Context) context.Context {
md := metadata.MD{
"taskID": strconv.FormatUint(f.taskID, 10),
"epoch": strconv.FormatUint(f.epoch, 10),
}
return metadata.NewContext(ctx, md)
}
示例8: ToStr
func ToStr(value interface{}, args ...int) (s string) {
switch v := value.(type) {
case bool:
s = strconv.FormatBool(v)
case float32:
s = strconv.FormatFloat(float64(v), 'f', argInt(args).Get(0, -1), argInt(args).Get(1, 32))
case float64:
s = strconv.FormatFloat(v, 'f', argInt(args).Get(0, -1), argInt(args).Get(1, 64))
case int:
s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
case int16:
s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
case int32:
s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
case int64:
s = strconv.FormatInt(v, argInt(args).Get(0, 10))
case uint:
s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
case uint16:
s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
case uint32:
s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
case uint64:
s = strconv.FormatUint(v, argInt(args).Get(0, 10))
case string:
s = v
default:
s = fmt.Sprintf("%v", v)
}
return s
}
示例9: storeSubscription
func (r *RequestBundle) storeSubscription(userID uint64, subscription *Subscription) error {
// start instrumentation
changes := map[string]interface{}{}
from := map[string]interface{}{}
old_user, err := r.GetUser(userID)
// add repo call to instrumentation
if err != nil {
return err
}
old_sub := old_user.Subscription
if old_sub.Expires != subscription.Expires {
changes["subscription_expires"] = subscription.Expires.Format(time.RFC3339)
from["subscription_expires"] = old_sub.Expires.Format(time.RFC3339)
}
if old_sub.ID != subscription.ID {
changes["subscription_id"] = subscription.ID
from["subscription_id"] = old_sub.ID
}
reply := r.Repo.client.MultiCall(func(mc *redis.MultiCall) {
mc.Hmset("users:"+strconv.FormatUint(userID, 10), changes)
mc.Zadd("users_by_subscription_expiration", subscription.Expires.Unix(), userID)
})
// add repo call to instrumentation
if reply.Err != nil {
r.Log.Error(reply.Err.Error())
return reply.Err
}
r.AuditMap("users:"+strconv.FormatUint(userID, 10), from, changes)
// stop instrumentation
return nil
}
示例10: Heartbeat
// Heartbeat checks the status of a follower.
func (t *HTTPTransport) Heartbeat(uri *url.URL, term, commitIndex, leaderID uint64) (uint64, error) {
// Construct URL.
u := *uri
u.Path = path.Join(u.Path, "raft/heartbeat")
// Set URL parameters.
v := &url.Values{}
v.Set("term", strconv.FormatUint(term, 10))
v.Set("commitIndex", strconv.FormatUint(commitIndex, 10))
v.Set("leaderID", strconv.FormatUint(leaderID, 10))
u.RawQuery = v.Encode()
// Send HTTP request.
resp, err := http.Get(u.String())
if err != nil {
return 0, err
}
_ = resp.Body.Close()
// Parse returned index.
newIndexString := resp.Header.Get("X-Raft-Index")
newIndex, err := strconv.ParseUint(newIndexString, 10, 64)
if err != nil {
return 0, fmt.Errorf("invalid index: %q", newIndexString)
}
// Parse returned error.
if s := resp.Header.Get("X-Raft-Error"); s != "" {
return newIndex, errors.New(s)
}
return newIndex, nil
}
示例11: createSubChannel
func (c *channel) createSubChannel(direction direction) (libchan.Sender, libchan.Receiver, error) {
if c.direction == inbound {
return nil, nil, errors.New("cannot create sub channel of an inbound channel")
}
referenceID := c.session.nextReferenceID()
headers := http.Header{}
headers.Set("libchan-ref", strconv.FormatUint(referenceID, 10))
headers.Set("libchan-parent-ref", strconv.FormatUint(c.referenceID, 10))
stream, streamErr := c.stream.CreateSubStream(headers, false)
if streamErr != nil {
return nil, nil, streamErr
}
subChannel := &channel{
referenceID: referenceID,
parentID: c.referenceID,
stream: stream,
session: c.session,
direction: direction,
}
c.session.channelC.L.Lock()
c.session.channels[referenceID] = subChannel
c.session.channelC.L.Unlock()
return subChannel, subChannel, nil
}
示例12: String
func (vr *VersionRecord) String() string {
buf := new(bytes.Buffer)
buf.WriteString(vr.stamp.Format(time.RFC3339Nano))
buf.WriteString(Delimiter1)
buf.WriteString(vr.cmd)
buf.WriteString(Delimiter1)
buf.WriteString(vr.ra.String())
buf.WriteString(Delimiter1)
buf.WriteString(vr.la.String())
buf.WriteString(Delimiter1)
buf.WriteString(strconv.FormatInt(int64(vr.version), 10))
buf.WriteString(Delimiter1)
buf.WriteString(strconv.FormatUint(vr.services, 10))
buf.WriteString(Delimiter1)
buf.WriteString(strconv.FormatInt(vr.sent.Unix(), 10))
buf.WriteString(Delimiter1)
buf.WriteString(vr.raddr.String())
buf.WriteString(Delimiter1)
buf.WriteString(vr.laddr.String())
buf.WriteString(Delimiter1)
buf.WriteString(strconv.FormatInt(int64(vr.block), 10))
buf.WriteString(Delimiter1)
buf.WriteString(strconv.FormatBool(vr.relay))
buf.WriteString(Delimiter1)
buf.WriteString(strconv.FormatUint(vr.nonce, 10))
buf.WriteString(Delimiter1)
buf.WriteString(vr.agent)
return buf.String()
}
示例13: Unsubscribe
// Unsubscribe unsubscribes a replica from a topic on the broker.
func (c *Client) Unsubscribe(replicaID, topicID uint64) error {
var resp *http.Response
var err error
u := *c.LeaderURL()
for {
u.Path = "/messaging/subscriptions"
u.RawQuery = url.Values{
"replicaID": {strconv.FormatUint(replicaID, 10)},
"topicID": {strconv.FormatUint(topicID, 10)},
}.Encode()
req, _ := http.NewRequest("DELETE", u.String(), nil)
resp, err = http.DefaultClient.Do(req)
if err != nil {
return err
}
defer func() { _ = resp.Body.Close() }()
// If a temporary redirect occurs then update the leader and retry.
// If a non-204 status is returned then an error occurred.
if resp.StatusCode == http.StatusTemporaryRedirect {
redirectURL, err := url.Parse(resp.Header.Get("Location"))
if err != nil {
return fmt.Errorf("bad redirect: %s", resp.Header.Get("Location"))
}
u = *redirectURL
continue
} else if resp.StatusCode != http.StatusNoContent {
return errors.New(resp.Header.Get("X-Broker-Error"))
}
break
}
return nil
}
示例14: DeviceInodeString
func DeviceInodeString(dev, ino uint64) string {
if dev == 0 && ino == 0 {
return ""
} else {
return strconv.FormatUint(dev, 10) + ":" + strconv.FormatUint(ino, 10)
}
}
示例15: ReadFrom
// ReadFrom streams the log from a leader.
func (t *HTTPTransport) ReadFrom(uri *url.URL, id, term, index uint64) (io.ReadCloser, error) {
// Construct URL.
u := *uri
u.Path = path.Join(u.Path, "raft/stream")
// Set URL parameters.
v := &url.Values{}
v.Set("id", strconv.FormatUint(id, 10))
v.Set("term", strconv.FormatUint(term, 10))
v.Set("index", strconv.FormatUint(index, 10))
u.RawQuery = v.Encode()
// Send HTTP request.
resp, err := http.Get(u.String())
if err != nil {
return nil, err
}
// Parse returned error.
if s := resp.Header.Get("X-Raft-Error"); s != "" {
_ = resp.Body.Close()
return nil, errors.New(s)
}
return resp.Body, nil
}