本文整理汇总了Golang中qiniu/api/v6/rs.PutPolicy.Token方法的典型用法代码示例。如果您正苦于以下问题:Golang PutPolicy.Token方法的具体用法?Golang PutPolicy.Token怎么用?Golang PutPolicy.Token使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类qiniu/api/v6/rs.PutPolicy
的用法示例。
在下文中一共展示了PutPolicy.Token方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: GenerateToken
func GenerateToken(cmd string, params ...string) {
if len(params) >= 2 {
bucket := params[0]
key := params[1]
time := 360000
if len(params) == 3 {
time, _ = strconv.Atoi(params[2])
}
gErr := accountS.Get()
if gErr != nil {
fmt.Println(gErr)
return
}
mac := digest.Mac{accountS.AccessKey, []byte(accountS.SecretKey)}
policy := rs.PutPolicy{
Scope: fmt.Sprintf("%s:%s", bucket, key),
Expires: uint32(time),
}
uptoken := policy.Token(&mac)
fmt.Printf("Token:: %s\n", uptoken)
} else {
CmdHelp(cmd)
}
}
示例2: TestPrivateImageView
func TestPrivateImageView(t *testing.T) {
//首先上传一个图片 用于测试
policy := rs.PutPolicy{
Scope: bucket + ":" + key,
}
err := io.PutFile(nil, nil, policy.Token(nil), key, localFile, nil)
if err != nil {
t.Errorf("TestPrivateImageView failed: %v", err)
return
}
rawUrl := makeUrl(key)
iv := ImageView{
Mode: 2,
Height: 250,
Quality: 80,
}
imageViewUrl := iv.MakeRequest(rawUrl)
p := rs.GetPolicy{}
imageViewUrlWithToken := p.MakeRequest(imageViewUrl, nil)
resp, err := http.DefaultClient.Get(imageViewUrlWithToken)
if err != nil {
t.Errorf("TestPrivateImageView failed: %v", err)
return
}
defer resp.Body.Close()
if (resp.StatusCode / 100) != 2 {
t.Errorf("TestPrivateImageView failed: resp.StatusCode = %v", resp.StatusCode)
return
}
}
示例3: upFile
func upFile(localFile, bucketName, key string) error {
policy := rs.PutPolicy{
Scope: bucketName + ":" + key,
}
return qio.PutFile(nil, nil, policy.Token(nil), key, localFile, nil)
}
示例4: uptoken
// @gist uptoken
func uptoken(bucketName string) string {
putPolicy := rs.PutPolicy{
Scope: bucketName,
// CallbackUrl: callbackUrl,
// CallbackBody: callbackBody,
// ReturnUrl: returnUrl,
// ReturnBody: returnBody,
// AsyncOps: asyncOps,
// EndUser: endUser,
// Expires: expires,
}
return putPolicy.Token(nil)
}
示例5: TestAll
func TestAll(t *testing.T) {
policy := rs.PutPolicy{
Scope: bucket,
}
token := policy.Token(nil)
params := map[string]string{"x:1": "1"}
extra := &PutExtra{
ChunkSize: 128,
MimeType: "text/plain",
Notify: blockNotify,
Params: params,
}
testPut(t, token, nil)
testPutWithoutKey(t, token, extra)
testPutFile(t, token, extra)
testPutFileWithoutKey(t, token, extra)
testXVar(t, token, extra)
}
示例6: FormPut
func FormPut(cmd string, params ...string) {
if len(params) == 3 || len(params) == 4 || len(params) == 5 || len(params) == 6 {
bucket := params[0]
key := params[1]
localFile := params[2]
mimeType := ""
upHost := ""
overwrite := false
optionalParams := params[3:]
for _, param := range optionalParams {
if val, pErr := strconv.ParseBool(param); pErr == nil {
overwrite = val
continue
}
if strings.HasPrefix(param, "http://") || strings.HasPrefix(param, "https://") {
upHost = param
continue
}
mimeType = param
}
gErr := accountS.Get()
if gErr != nil {
fmt.Println(gErr)
return
}
mac := digest.Mac{accountS.AccessKey, []byte(accountS.SecretKey)}
policy := rs.PutPolicy{}
if overwrite {
policy.Scope = fmt.Sprintf("%s:%s", bucket, key)
} else {
policy.Scope = bucket
}
putExtra := fio.PutExtra{}
if mimeType != "" {
putExtra.MimeType = mimeType
}
if upHost != "" {
conf.UP_HOST = upHost
}
uptoken := policy.Token(&mac)
putRet := fio.PutRet{}
startTime := time.Now()
fStat, statErr := os.Stat(localFile)
if statErr != nil {
fmt.Println("Local file error", statErr)
return
}
fsize := fStat.Size()
putClient := rpc.NewClient("")
fmt.Println(fmt.Sprintf("Uploading %s => %s : %s ...", localFile, bucket, key))
doneSignal := make(chan bool)
go func(ch chan bool) {
progressSigns := []string{"|", "/", "-", "\\", "|"}
for {
for _, p := range progressSigns {
fmt.Print("\rProgress: ", p)
os.Stdout.Sync()
<-time.After(time.Millisecond * 200)
}
select {
case <-ch:
break
}
}
}(doneSignal)
err := fio.PutFile(putClient, nil, &putRet, uptoken, key, localFile, &putExtra)
doneSignal <- true
fmt.Print("\rProgress: 100%")
os.Stdout.Sync()
fmt.Println()
if err != nil {
if v, ok := err.(*rpc.ErrorInfo); ok {
fmt.Println(fmt.Sprintf("Put file error, %d %s, Reqid: %s", v.Code, v.Err, v.Reqid))
} else {
fmt.Println("Put file error,", err)
}
} else {
fmt.Println("Put file", localFile, "=>", bucket, ":", putRet.Key, "(", putRet.Hash, ")", "success!")
}
lastNano := time.Now().UnixNano() - startTime.UnixNano()
lastTime := fmt.Sprintf("%.2f", float32(lastNano)/1e9)
avgSpeed := fmt.Sprintf("%.1f", float32(fsize)*1e6/float32(lastNano))
fmt.Println("Last time:", lastTime, "s, Average Speed:", avgSpeed, "KB/s")
} else {
示例7: ResumablePut
func ResumablePut(cmd string, params ...string) {
if len(params) == 3 || len(params) == 4 || len(params) == 5 || len(params) == 6 {
bucket := params[0]
key := params[1]
localFile := params[2]
mimeType := ""
upHost := ""
overwrite := false
optionalParams := params[3:]
for _, param := range optionalParams {
if val, pErr := strconv.ParseBool(param); pErr == nil {
overwrite = val
continue
}
if strings.HasPrefix(param, "http://") || strings.HasPrefix(param, "https://") {
upHost = param
continue
}
mimeType = param
}
gErr := accountS.Get()
if gErr != nil {
fmt.Println(gErr)
return
}
fStat, statErr := os.Stat(localFile)
if statErr != nil {
fmt.Println("Local file error", statErr)
return
}
fsize := fStat.Size()
mac := digest.Mac{accountS.AccessKey, []byte(accountS.SecretKey)}
policy := rs.PutPolicy{}
if overwrite {
policy.Scope = fmt.Sprintf("%s:%s", bucket, key)
} else {
policy.Scope = bucket
}
putExtra := rio.PutExtra{}
if mimeType != "" {
putExtra.MimeType = mimeType
}
if upHost != "" {
conf.UP_HOST = upHost
}
progressHandler := ProgressHandler{
rwLock: &sync.RWMutex{},
fsize: fsize,
offsets: make(map[int]int64, 0),
}
putExtra.Notify = progressHandler.Notify
putExtra.NotifyErr = progressHandler.NotifyErr
uptoken := policy.Token(&mac)
putRet := rio.PutRet{}
startTime := time.Now()
rio.SetSettings(&upSettings)
putClient := rio.NewClient(uptoken, "")
fmt.Println(fmt.Sprintf("Uploading %s => %s : %s ...", localFile, bucket, key))
err := rio.PutFile(putClient, nil, &putRet, key, localFile, &putExtra)
fmt.Println()
if err != nil {
if v, ok := err.(*rpc.ErrorInfo); ok {
fmt.Println(fmt.Sprintf("Put file error, %d %s, Reqid: %s", v.Code, v.Err, v.Reqid))
} else {
fmt.Println("Put file error,", err)
}
} else {
fmt.Println("Put file", localFile, "=>", bucket, ":", putRet.Key, "(", putRet.Hash, ")", "success!")
}
lastNano := time.Now().UnixNano() - startTime.UnixNano()
lastTime := fmt.Sprintf("%.2f", float32(lastNano)/1e9)
avgSpeed := fmt.Sprintf("%.1f", float32(fsize)*1e6/float32(lastNano))
fmt.Println("Last time:", lastTime, "s, Average Speed:", avgSpeed, "KB/s")
} else {
CmdHelp(cmd)
}
}
示例8: QiniuUpload
//.........这里部分代码省略.........
}
} else {
//check leveldb
ldbFlmd, err := ldb.Get([]byte(ldbKey), nil)
flmd, _ := strconv.ParseInt(string(ldbFlmd), 10, 64)
//not exist, return ErrNotFound
//check last modified
if err == nil && localFlmd == flmd {
log.Debug("Skip by local log for file", localFpath)
atomic.AddInt64(&skippedFileCount, 1)
continue
}
}
//worker
upCounter += 1
if upCounter%threadThreshold == 0 {
upWorkGroup.Wait()
}
upWorkGroup.Add(1)
//start to upload
go func() {
defer upWorkGroup.Done()
policy := rs.PutPolicy{}
policy.Scope = uploadConfig.Bucket
if uploadConfig.Overwrite {
policy.Scope = fmt.Sprintf("%s:%s", uploadConfig.Bucket, uploadFileKey)
policy.InsertOnly = 0
}
policy.Expires = 30 * 24 * 3600
uptoken := policy.Token(&mac)
if fsize > putThreshold {
var putClient rpc.Client
if transport != nil {
putClient = rio.NewClientEx(uptoken, transport, uploadConfig.BindUpIp)
} else {
putClient = rio.NewClient(uptoken, uploadConfig.BindUpIp)
}
putRet := rio.PutRet{}
putExtra := rio.PutExtra{}
progressFkey := Md5Hex(fmt.Sprintf("%s:%s|%s:%s", uploadConfig.SrcDir, uploadConfig.Bucket, localFpath, uploadFileKey))
progressFname := fmt.Sprintf("%s.progress", progressFkey)
progressFpath := filepath.Join(storePath, progressFname)
putExtra.ProgressFile = progressFpath
err := rio.PutFile(putClient, nil, &putRet, uploadFileKey, localFilePath, &putExtra)
if err != nil {
atomic.AddInt64(&failureFileCount, 1)
if pErr, ok := err.(*rpc.ErrorInfo); ok {
log.Errorf("Put file `%s' => `%s' failed due to `%s'", localFilePath, uploadFileKey, pErr.Err)
} else {
log.Errorf("Put file `%s' => `%s' failed due to `%s'", localFilePath, uploadFileKey, err)
}
} else {
os.Remove(progressFpath)
atomic.AddInt64(&successFileCount, 1)
perr := ldb.Put([]byte(ldbKey), []byte(fmt.Sprintf("%d", localFlmd)), &ldbWOpt)
if perr != nil {
log.Errorf("Put key `%s' into leveldb error due to `%s'", ldbKey, perr)
}
}
} else {
示例9: Sync
func Sync(mac *digest.Mac, srcResUrl, bucket, key, upHostIp string) (hash string, err error) {
if exists, cErr := checkExists(mac, bucket, key); cErr != nil {
err = cErr
return
} else if exists {
err = errors.New("File with same key already exists in bucket")
return
}
syncProgress := SyncProgress{}
//read from the local progress file if exists, file name by md5(bucket+":"+key)
progressFile := createProgressFileName(bucket, key)
if statInfo, statErr := os.Stat(progressFile); statErr == nil {
//check file last modified time, if older than one week, ignore
if statInfo.ModTime().Add(time.Hour * 24 * 5).After(time.Now()) {
//try read old progress
progressFh, openErr := os.Open(progressFile)
if openErr == nil {
decoder := json.NewDecoder(progressFh)
decoder.Decode(&syncProgress)
progressFh.Close()
}
}
}
//check offset valid or not
if syncProgress.Offset%BLOCK_SIZE != 0 {
log.Info("Invalid offset from progress file,", syncProgress.Offset)
syncProgress.Offset = 0
syncProgress.TotalSize = 0
syncProgress.BlkCtxs = make([]rio.BlkputRet, 0)
}
//check offset and blk ctxs
if syncProgress.Offset != 0 && syncProgress.BlkCtxs != nil {
if int(syncProgress.Offset/BLOCK_SIZE) != len(syncProgress.BlkCtxs) {
log.Info("Invalid offset and block contexts")
syncProgress.Offset = 0
syncProgress.TotalSize = 0
syncProgress.BlkCtxs = make([]rio.BlkputRet, 0)
}
}
//check blk ctxs, when no progress found
if syncProgress.Offset == 0 || syncProgress.BlkCtxs == nil {
syncProgress.Offset = 0
syncProgress.TotalSize = 0
syncProgress.BlkCtxs = make([]rio.BlkputRet, 0)
}
//get total size
totalSize, hErr := getRemoteFileLength(srcResUrl)
if hErr != nil {
err = hErr
return
}
if totalSize != syncProgress.TotalSize {
if syncProgress.TotalSize != 0 {
log.Info("Remote file length changed, progress file out of date")
}
syncProgress.Offset = 0
syncProgress.TotalSize = totalSize
syncProgress.BlkCtxs = make([]rio.BlkputRet, 0)
}
//get total block count
totalBlkCnt := 0
if totalSize%BLOCK_SIZE == 0 {
totalBlkCnt = int(totalSize / BLOCK_SIZE)
} else {
totalBlkCnt = int(totalSize/BLOCK_SIZE) + 1
}
//init the range offset
rangeStartOffset := syncProgress.Offset
fromBlkIndex := int(rangeStartOffset / BLOCK_SIZE)
lastBlock := false
//create upload token
policy := rs.PutPolicy{Scope: bucket}
//token is valid for one year
policy.Expires = 3600 * 24 * 365
uptoken := policy.Token(mac)
putClient := rio.NewClient(uptoken, upHostIp)
//range get and mkblk upload
for blkIndex := fromBlkIndex; blkIndex < totalBlkCnt; blkIndex++ {
if blkIndex == totalBlkCnt-1 {
lastBlock = true
}
syncPercent := fmt.Sprintf("%.2f", float64(blkIndex+1)*100.0/float64(totalBlkCnt))
log.Info(fmt.Sprintf("Syncing block %d [%s%%] ...", blkIndex, syncPercent))
blkCtx, pErr := rangeMkblkPipe(srcResUrl, rangeStartOffset, BLOCK_SIZE, lastBlock, putClient)
if pErr != nil {
log.Error(pErr.Error())
time.Sleep(RETRY_INTERVAL)
//.........这里部分代码省略.........