├── test.c ├── tips.txt ├── contracts.go ├── README.md ├── .gitignore ├── bcs_test.go ├── common.go ├── superfile.go ├── reverse.c ├── superfile_test.go ├── tcp.c ├── bucket_test.go ├── bcs.go ├── bucket.go ├── http_client.go ├── object_test.go ├── object.go └── LICENSE /test.c: -------------------------------------------------------------------------------- 1 | #include "polymorphism.h" 2 | void (*f) (); 3 | 4 | int a = 0; 5 | void foo() { 6 | a++; 7 | } 8 | 9 | int main() { 10 | f = foo; 11 | f = &foo; 12 | f(); 13 | (*f)(); 14 | (**f)(); 15 | (***f)(); 16 | return a; 17 | } 18 | -------------------------------------------------------------------------------- /tips.txt: -------------------------------------------------------------------------------- 1 | copy and move objects 2 | list objects with prefix 3 | post to upload object 4 | bucket name or file name with blank 5 | more test of ACL 6 | ok: acl of buckets and objects 7 | ok: superfile 8 | 9 | 10 | create objects with dir will create all dirs 11 | -------------------------------------------------------------------------------- /contracts.go: -------------------------------------------------------------------------------- 1 | package bcsgo 2 | 3 | type ObjectCollection struct { 4 | ObjectTotal int `json:"object_total"` 5 | Start int `json:"start"` 6 | Limit int `json:"limit"` 7 | Bucket string `json:"bucket"` 8 | Objects []*Object `json:"object_list"` 9 | } 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | bcsgo 2 | ================ 3 | 4 | Golang Baidu BCS SDK 5 | 6 | 百度云存储服务Go语言SDK 7 | 8 | Baidu Official BCS Doc: [http://developer.baidu.com/wiki/index.php?title=docs/cplat/bcs](http://developer.baidu.com/wiki/index.php?title=docs/cplat/bcs) 9 | 10 | [Go Walker 文档](http://gowalker.org/github.com/eggfly/bcsgo) 11 | 12 | 后续想法: 13 | 14 | 1. 基于此SDK的Go语言版本的免费云网盘客户端 15 | 2. 高可用性的开放图床WebApp,支持用户自定义防盗链 16 | 3. 图片较多的静态站点和图片收集和分析 17 | 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | # eggfly 24 | baidu-bcs-sdk-go 25 | bcs-go 26 | test.txt 27 | coverage.out 28 | cover.html 29 | -------------------------------------------------------------------------------- /bcs_test.go: -------------------------------------------------------------------------------- 1 | package bcsgo 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | var ak = "zaTGAk9k6qoRaVoVcTCRGbjZ" 8 | var sk = "r7ay1xOM12s4afPUqRZ9f53su8OF6lwj" 9 | var bcs = NewBCS(ak, sk) 10 | 11 | func init() { 12 | // DEBUG = true 13 | } 14 | 15 | func TestBCSListBuckets(t *testing.T) { 16 | buckets, e := bcs.ListBuckets() 17 | if e != nil { 18 | t.Error(e) 19 | } 20 | if buckets == nil { 21 | t.Error("buckets list is nil") 22 | } 23 | } 24 | 25 | func TestBCSNewBucket(t *testing.T) { 26 | bucket := bcs.Bucket("mockBucket") 27 | if bucket == nil { 28 | t.Error("new bucket shouldn't be nil") 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /common.go: -------------------------------------------------------------------------------- 1 | package bcsgo 2 | 3 | const ( 4 | GET = "GET" 5 | POST = "POST" 6 | PUT = "PUT" 7 | HEAD = "HEAD" 8 | DELETE = "DELETE" 9 | ) 10 | 11 | const ( 12 | BCS_HOST = "http://bcs.duapp.com" 13 | ) 14 | 15 | const ( 16 | ACL_PRIVATE = "private" 17 | ACL_PUBLIC_READ = "public-read" 18 | ACL_PUBLIC_WRITE = "public-write" 19 | ACL_PUBLIC_READ_WRITE = "public-read-write" 20 | ACL_PUBLIC_CONTROL = "public-control" 21 | ) 22 | 23 | const ( 24 | HEADER_COPY_SOURCE = "x-bs-copy-source" 25 | HEADER_ACL = "X-Bs-Acl" 26 | HEADER_VERSION = "X-Bs-Version" 27 | HEADER_FILESIZE = "X-Bs-File-Size" 28 | HEADER_ETAG = "Etag" 29 | HEADER_CONTENT_MD5 = "Content-Md5" 30 | ) 31 | 32 | var DEBUG bool = false 33 | var DEBUG_REQUEST_BODY = false 34 | -------------------------------------------------------------------------------- /superfile.go: -------------------------------------------------------------------------------- 1 | package bcsgo 2 | 3 | import ( 4 | // "encoding/json" 5 | "fmt" 6 | // "io" 7 | // "net/http" 8 | "strings" 9 | ) 10 | 11 | type Superfile struct { 12 | Object 13 | Objects []*Object 14 | } 15 | 16 | func (this *Superfile) putSuperfileUrl() string { 17 | return this.putUrl() + "&superfile=1" 18 | } 19 | func (this *Superfile) Put() error { 20 | link := this.putSuperfileUrl() 21 | parts := make([]string, 0) 22 | for i, item := range this.Objects { 23 | parts = append(parts, fmt.Sprintf(`"part_%d": {"url": "%s", "etag":"%s"}`, i, item.refStr(), item.ContentMD5)) 24 | } 25 | partsStr := strings.Join(parts, ",") 26 | meta := fmt.Sprintf(`{"object_list": {%s}}`, partsStr) 27 | reader := strings.NewReader(meta) 28 | resp, _, err := this.bucket.bcs.httpClient.Put(link, reader, int64(len(meta)), nil) 29 | err = mergeResponseError(err, resp) 30 | if err == nil { 31 | this.ContentMD5 = resp.Header.Get(HEADER_ETAG) 32 | this.VersionKey = resp.Header.Get(HEADER_VERSION) 33 | } 34 | return err 35 | } 36 | -------------------------------------------------------------------------------- /reverse.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // 字符串翻转函数 5 | void reverse_str(char* strInput, int nStart, int nEnd) 6 | { 7 | if (nStart >= nEnd || nStart < 0 || nEnd >= strlen(strInput)) { 8 | return; 9 | } 10 | while(nStart < nEnd) { 11 | char cTemp = strInput[nStart]; 12 | strInput[nStart] = strInput[nEnd]; 13 | strInput[nEnd] = cTemp; 14 | nStart++; 15 | nEnd--; 16 | } 17 | } 18 | 19 | void reverse_domain(char* strInput) 20 | { 21 | reverse_str(strInput, 0, strlen(strInput) - 1); 22 | 23 | // 域名中的每个单词反转 24 | char* strStart = strInput; 25 | int nStart = 0; 26 | int nEnd = 0; 27 | while( *strInput != '\0') 28 | { 29 | if ( *strInput == '.') 30 | { 31 | reverse_str(strStart, nStart, nEnd - 1); 32 | nStart = nEnd + 1; 33 | strStart = strInput; 34 | } 35 | nEnd ++; 36 | strInput ++; 37 | } 38 | } 39 | 40 | int main() 41 | { 42 | char a[] = "www.mi.com"; 43 | reverse_domain(a); 44 | printf("%s", a); 45 | } 46 | -------------------------------------------------------------------------------- /superfile_test.go: -------------------------------------------------------------------------------- 1 | package bcsgo 2 | 3 | import ( 4 | // "fmt" 5 | "testing" 6 | "time" 7 | ) 8 | 9 | var bucketForSuperfileTest *Bucket 10 | 11 | func TestSuperfileInit(t *testing.T) { 12 | bucket := createBucketTempForTest(t) 13 | bucketForSuperfileTest = bucket 14 | 15 | createTestFile(_TEST_NAME, 256*1024) 16 | } 17 | 18 | func TestSuperfilePutAndDelete(t *testing.T) { 19 | bucket := bucketForSuperfileTest 20 | // todo file name with blank char 21 | putFile := func(path, localFile string) *Object { 22 | testObj := bucket.Object(path) 23 | testObj, err := testObj.PutFile(localFile) 24 | if err != nil { 25 | t.Error(err) 26 | } 27 | if testObj.AbsolutePath != path { 28 | t.Error("testObj.AbsolutePath != path", testObj.AbsolutePath, path) 29 | } 30 | return testObj 31 | } 32 | deleteFile := func(testObj *Object) { 33 | deleteErr := testObj.Delete() 34 | if deleteErr != nil { 35 | t.Error(deleteErr) 36 | } 37 | } 38 | dupFileTimes := func(absPath string, obj *Object, times int) *Superfile { 39 | repeats := make([]*Object, 0) 40 | for i := 0; i < times; i++ { 41 | repeats = append(repeats, obj) 42 | } 43 | s := bucket.Superfile(absPath, repeats) 44 | err := s.Put() 45 | if err != nil { 46 | t.Error(err) 47 | } 48 | return s 49 | } 50 | obj := putFile("/testDir/test.txt", _TEST_NAME) 51 | // DEBUG_REQUEST_BODY = true 52 | s := dupFileTimes("/testDir/test.txt", obj, 1024) 53 | 54 | deleteFile(&s.Object) 55 | } 56 | 57 | func TestSuperfileFinalize(t *testing.T) { 58 | time.Sleep(time.Second) 59 | deleteBucketForTest(t, bucketForSuperfileTest) 60 | bucketForSuperfileTest = nil 61 | deleteTestFile(_TEST_NAME) 62 | } 63 | -------------------------------------------------------------------------------- /tcp.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | int main() { 12 | struct sockaddr_in serveraAddr, clientAddr; 13 | socklen_t clientAddrLen; 14 | int nFd = 0, linkFd = 0; 15 | int nRet = 0; 16 | int nReadLen = 0; 17 | char szBuff[BUFSIZ] = { 18 | 0 19 | }; 20 | 21 | /* 创建一个socket描述符 */ 22 | nFd = socket(AF_INET, SOCK_STREAM, 0); 23 | if (-1 == nFd) { 24 | perror("socket:"); 25 | return -1; 26 | } 27 | 28 | /* 给本地的socket地址赋值 */ 29 | memset( & serveraAddr, 0, sizeof(struct sockaddr_in)); 30 | serveraAddr.sin_family = AF_INET; //以ipv4协议进行连接 31 | serveraAddr.sin_addr.s_addr = htonl(INADDR_ANY); //接收所有客户端ip的连接 32 | serveraAddr.sin_port = htons(1111); //接收8080端口发来的连接 33 | 34 | /* 当TCP的连接的状态是TCP_WAIT状态的时候, 可以通过设置SO_REUSEADDR 35 | 选项来强制使用属于TIME_WAIT状态的连接的socket*/ 36 | int isReuse = 1; 37 | setsockopt(nFd, SOL_SOCKET, SO_REUSEADDR, (const char * ) & isReuse, sizeof(isReuse)); 38 | 39 | /* 将该socket的描述符和本地的套接字地址绑定起来 */ 40 | nRet = bind(nFd, (struct sockaddr * ) & serveraAddr, sizeof(serveraAddr)); 41 | if (-1 == nRet) { 42 | perror("bind:"); 43 | return -1; 44 | } 45 | 46 | /* 设置该套接口在监听状态 */ 47 | listen(nFd, 1); 48 | 49 | /* 等待客户端发来的tcp连接 ,当客户端连接进来之后,返回两个之间的唯一的socket连接,存放在linkFd之中*/ 50 | clientAddrLen = sizeof(struct sockaddr_in); 51 | linkFd = accept(nFd, (struct sockaddr * ) & clientAddr, & clientAddrLen); 52 | if (-1 == linkFd) { 53 | perror("accept:"); 54 | return -1; 55 | } 56 | 57 | /* 把连接进来的客户端地址和端口打印出来 */ 58 | printf("connect %s %d successful\n", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port)); 59 | 60 | /* 循环的读取客户端发来的数据 */ 61 | FILE * out; 62 | if ((out = fopen("app.data", "wt")) == NULL) { 63 | fprintf(stderr, "Cannot open output file./n"); 64 | return 1; 65 | } 66 | while (1) { 67 | memset(szBuff, 0, BUFSIZ); 68 | nReadLen = read(linkFd, szBuff, BUFSIZ); 69 | if (nReadLen > 0) { 70 | printf("read data: %s\n", szBuff); 71 | fprintf(out, "%s\n", szBuff); 72 | fflush(out); 73 | } 74 | } 75 | fclose(out); 76 | return 0; 77 | } 78 | -------------------------------------------------------------------------------- /bucket_test.go: -------------------------------------------------------------------------------- 1 | package bcsgo 2 | 3 | import ( 4 | "strconv" 5 | "testing" 6 | "time" 7 | ) 8 | 9 | func randomGlobalBucketName(index int) string { 10 | return ak[:2] + "-sdk-" + strconv.FormatInt(time.Now().Unix(), 10)[5:] + "-" + strconv.Itoa(index) 11 | } 12 | 13 | func createBucketTempForTest(t *testing.T) *Bucket { 14 | bucketName := randomGlobalBucketName(1) 15 | bucket := bcs.Bucket(bucketName) 16 | err := bucket.Create() 17 | if err != nil { 18 | t.Error(err) 19 | } 20 | return bucket 21 | } 22 | 23 | func deleteBucketForTest(t *testing.T, bucket *Bucket) { 24 | deleteErr := bucket.Delete() 25 | if deleteErr != nil { 26 | t.Error(deleteErr) 27 | } 28 | } 29 | 30 | func TestBucketCreateWithACLAndDelete(t *testing.T) { 31 | bucketName := randomGlobalBucketName(1) 32 | newBucket := bcs.Bucket(bucketName) 33 | bucketErr := newBucket.CreateWithACL(ACL_PUBLIC_READ) 34 | if bucketErr != nil { 35 | t.Error(bucketErr) 36 | } 37 | 38 | // bucketACL, bucketACLErr := newBucket.GetACL() 39 | // expectedBucketACL := fmt.Sprintf(`{"statements":[{"action":["*"],"effect":"allow","resource":["testsml2\/"],"user":["psp:egg90"]},{"action":["get_object"],"effect":"allow","resource":["%s\/"],"user":["*"]}]}`, bucketName) 40 | // if bucketACLErr != nil { 41 | // fmt.Println(bucketACLErr) 42 | // t.Fail() 43 | // } 44 | // if bucketACL != expectedBucketACL { 45 | // fmt.Println(bucketACL) 46 | // fmt.Println(expectedBucketACL) 47 | // t.Fail() 48 | // } 49 | 50 | bucketErr = newBucket.Delete() 51 | if bucketErr != nil { 52 | t.Error(bucketErr) 53 | } 54 | } 55 | 56 | func TestBucketCreateWithInvalidName(t *testing.T) { 57 | newBucket := bcs.Bucket("testErrorBucket") 58 | bucketErr := newBucket.Create() 59 | // It shall be failed. 60 | if bucketErr == nil { 61 | t.Error("create bucket with invaid name should failed") 62 | } 63 | } 64 | 65 | func TestBucketACL(t *testing.T) { 66 | bucket := createBucketTempForTest(t) 67 | 68 | acl, aclErr := bucket.GetACL() 69 | if aclErr != nil { 70 | t.Error(aclErr) 71 | } 72 | if acl == "" { 73 | t.Error("acl string shouldn't be nil") 74 | } 75 | 76 | setACLCheckError := func(acl string) { 77 | putErr := bucket.SetACL(acl) 78 | if putErr != nil { 79 | t.Error(putErr) 80 | } 81 | } 82 | 83 | setACLCheckError(ACL_PUBLIC_CONTROL) 84 | setACLCheckError(ACL_PUBLIC_READ) 85 | setACLCheckError(ACL_PUBLIC_WRITE) 86 | setACLCheckError(ACL_PUBLIC_READ_WRITE) 87 | setACLCheckError(ACL_PRIVATE) 88 | 89 | deleteBucketForTest(t, bucket) 90 | } 91 | -------------------------------------------------------------------------------- /bcs.go: -------------------------------------------------------------------------------- 1 | package bcsgo 2 | 3 | import ( 4 | "crypto/hmac" 5 | "crypto/sha1" 6 | "encoding/base64" 7 | "encoding/json" 8 | "fmt" 9 | "net/url" 10 | "strings" 11 | ) 12 | 13 | type BCS struct { 14 | ak, sk string 15 | httpClient *HttpClient 16 | } 17 | 18 | func NewBCS(ak, sk string) *BCS { 19 | return &BCS{ak, sk, NewHttpClient()} 20 | } 21 | 22 | func (this *BCS) ListBuckets() ([]*Bucket, error) { 23 | link := this.getUrl() 24 | _, data, err := this.httpClient.Get(link) 25 | if err != nil { 26 | return nil, err 27 | } else { 28 | list := []*Bucket{} 29 | err := json.Unmarshal(data, &list) 30 | for i, _ := range list { 31 | list[i].bcs = this 32 | } 33 | return list, err 34 | } 35 | } 36 | func (this *BCS) Bucket(bucketName string) *Bucket { 37 | return &Bucket{this, bucketName} 38 | } 39 | 40 | func (this *BCS) getUrl() string { 41 | return this.restUrl(GET, "", "/") 42 | } 43 | func (this *BCS) restUrl(method, bucket, object string) string { 44 | return this.urlWithSign(method, bucket, object, "", "", "") 45 | } 46 | func (this *BCS) restUrlExtra(method, bucket, object, time, ip, size string) string { 47 | return this.urlWithSign(method, bucket, object, time, ip, size) 48 | } 49 | func (this *BCS) urlWithSign(method, bucket, object, time, ip, size string) string { 50 | return fmt.Sprintf("%s?sign=%s", this.urlWithoutSign(bucket, object), this.sign(method, bucket, object, time, ip, size)) 51 | } 52 | func (this *BCS) urlWithoutSign(bucket, object string) string { 53 | return fmt.Sprintf("%s/%s%s", BCS_HOST, bucket, "/"+url.QueryEscape(object[1:])) 54 | // return fmt.Sprintf("%s/%s%s", BCS_HOST, bucket, "/"+object[1:]) 55 | } 56 | func (this *BCS) sign(m, b, o, t, i, s string) string { 57 | flag := "" 58 | ss := "" 59 | flag += "M" 60 | ss += "Method=" + m + "\n" 61 | flag += "B" 62 | ss += "Bucket=" + b + "\n" 63 | flag += "O" 64 | ss += "Object=" + o + "\n" 65 | if t != "" { 66 | flag += "T" 67 | ss += "Time=" + t + "\n" 68 | } 69 | if i != "" { 70 | flag += "I" 71 | ss += "Ip=" + i + "\n" 72 | } 73 | if s != "" { 74 | flag += "S" 75 | ss += "Size=" + s + "\n" 76 | } 77 | ss = flag + "\n" + ss 78 | h := func(sk, body string) string { 79 | hash := hmac.New(sha1.New, []byte(sk)) 80 | hash.Write([]byte(body)) 81 | digest := hash.Sum(nil) 82 | sign := base64.StdEncoding.EncodeToString(digest) 83 | sign = strings.TrimSpace(sign) 84 | sign = url.QueryEscape(sign) 85 | return sign 86 | } 87 | sign := h(this.sk, ss) 88 | final := fmt.Sprintf( 89 | "%s:%s:%s", 90 | flag, 91 | this.ak, 92 | sign) 93 | if t != "" { 94 | final += "&time=" + t 95 | } 96 | if i != "" { 97 | final += "&ip=" + i 98 | } 99 | if s != "" { 100 | final += "&size=" + s 101 | } 102 | return final 103 | } 104 | -------------------------------------------------------------------------------- /bucket.go: -------------------------------------------------------------------------------- 1 | package bcsgo 2 | 3 | import ( 4 | "encoding/json" 5 | "net/http" 6 | "net/url" 7 | "strconv" 8 | ) 9 | 10 | type Bucket struct { 11 | bcs *BCS 12 | Name string `json:"bucket_name"` 13 | } 14 | 15 | func (this *Bucket) getUrl() string { 16 | return this.bcs.restUrl(GET, this.Name, "/") 17 | } 18 | func (this *Bucket) getACLUrl() string { 19 | return this.getUrl() + "&acl=1" 20 | } 21 | func (this *Bucket) putUrl() string { 22 | return this.bcs.restUrl(PUT, this.Name, "/") 23 | } 24 | func (this *Bucket) putACLUrl() string { 25 | return this.putUrl() + "&acl=1" 26 | } 27 | func (this *Bucket) deleteUrl() string { 28 | return this.bcs.restUrl(DELETE, this.Name, "/") 29 | } 30 | func (this *Bucket) CreateWithACL(acl string) error { 31 | return this.createInner(acl) 32 | } 33 | func (this *Bucket) Create() error { 34 | return this.createInner("") 35 | } 36 | func (this *Bucket) createInner(acl string) error { 37 | link := this.putUrl() 38 | var modifyHeader func(*http.Header) 39 | if acl != "" { 40 | modifyHeader = func(header *http.Header) { 41 | header.Set(HEADER_ACL, acl) 42 | } 43 | } 44 | resp, _, err := this.bcs.httpClient.Put(link, nil, 0, modifyHeader) 45 | return mergeResponseError(err, resp) 46 | } 47 | func (this *Bucket) Delete() error { 48 | link := this.deleteUrl() 49 | resp, _, err := this.bcs.httpClient.Delete(link) 50 | return mergeResponseError(err, resp) 51 | } 52 | func (this *Bucket) Object(absolutePath string) *Object { 53 | if absolutePath[0] != '/' { 54 | panic("object name (aka absolute path) must start with '/'") 55 | } 56 | o := Object{} 57 | o.bucket = this 58 | o.AbsolutePath = absolutePath 59 | return &o 60 | } 61 | func (this *Bucket) Superfile(absolutePath string, objects []*Object) *Superfile { 62 | if absolutePath[0] != '/' { 63 | panic("object name (aka absolute path) must start with '/'") 64 | } 65 | s := Superfile{} 66 | s.bucket = this 67 | s.AbsolutePath = absolutePath 68 | s.Objects = objects 69 | return &s 70 | } 71 | func (this *Bucket) ListObjects(prefix string, start, limit int) (*ObjectCollection, error) { 72 | params := url.Values{} 73 | params.Set("start", strconv.Itoa(start)) 74 | params.Set("limit", strconv.Itoa(limit)) 75 | if prefix != "" { 76 | params.Set("prefix", prefix) 77 | } 78 | link := this.getUrl() + "&" + params.Encode() 79 | _, data, err := this.bcs.httpClient.Get(link) 80 | if err != nil { 81 | return nil, err 82 | } else { 83 | var objectsInfo ObjectCollection 84 | err := json.Unmarshal(data, &objectsInfo) 85 | if err != nil { 86 | return nil, err 87 | } else { 88 | for i, _ := range objectsInfo.Objects { 89 | objectsInfo.Objects[i].bucket = this 90 | } 91 | return &objectsInfo, nil 92 | } 93 | } 94 | } 95 | func (this *Bucket) GetACL() (string, error) { 96 | link := this.getACLUrl() 97 | resp, data, err := this.bcs.httpClient.Get(link) 98 | err = mergeResponseError(err, resp) 99 | return string(data), err 100 | } 101 | func (this *Bucket) SetACL(acl string) error { 102 | link := this.putACLUrl() 103 | modifyHeader := func(header *http.Header) { 104 | header.Set(HEADER_ACL, acl) 105 | } 106 | resp, _, err := this.bcs.httpClient.Put(link, nil, 0, modifyHeader) 107 | return mergeResponseError(err, resp) 108 | } 109 | -------------------------------------------------------------------------------- /http_client.go: -------------------------------------------------------------------------------- 1 | package bcsgo 2 | 3 | import ( 4 | "errors" 5 | "io" 6 | "io/ioutil" 7 | "log" 8 | "net/http" 9 | "net/http/httputil" 10 | "strconv" 11 | "time" 12 | ) 13 | 14 | type HttpClient struct { 15 | client *http.Client 16 | } 17 | 18 | func NewHttpClient() *HttpClient { 19 | return &HttpClient{&http.Client{}} 20 | } 21 | 22 | func (this *HttpClient) Get(url string) (*http.Response, []byte, error) { 23 | return this.createAndDoRequestForResult(GET, url, nil, nil) 24 | } 25 | func (this *HttpClient) Put(url string, data io.Reader, size int64, modifyHeader func(header *http.Header)) (*http.Response, []byte, error) { 26 | customRequest := func(req *http.Request) { 27 | req.ContentLength = size 28 | if modifyHeader != nil { 29 | modifyHeader(&req.Header) 30 | } 31 | } 32 | return this.createAndDoRequestForResult(PUT, url, data, customRequest) 33 | } 34 | func (this *HttpClient) Head(url string) (*http.Response, []byte, error) { 35 | return this.createAndDoRequestForResult(HEAD, url, nil, nil) 36 | } 37 | func (this *HttpClient) Delete(url string) (*http.Response, []byte, error) { 38 | return this.createAndDoRequestForResult(DELETE, url, nil, nil) 39 | } 40 | func (this *HttpClient) dumpRequest(req *http.Request) { 41 | if DEBUG { 42 | dump, dumpErr := httputil.DumpRequestOut(req, DEBUG_REQUEST_BODY) 43 | if dumpErr != nil { 44 | log.Println("error when dump request:", dumpErr) 45 | } 46 | log.Println("*** request dump ***") 47 | log.Println(string(dump)) 48 | } 49 | } 50 | func (this *HttpClient) createAndDoRequestForResult(method string, url string, data io.Reader, customRequest func(*http.Request)) (*http.Response, []byte, error) { 51 | req, err := http.NewRequest(method, url, data) 52 | if err != nil { 53 | return nil, nil, err 54 | } 55 | if customRequest != nil { 56 | customRequest(req) 57 | } 58 | this.dumpRequest(req) 59 | 60 | var oldTime time.Time 61 | if DEBUG { 62 | oldTime = time.Now() 63 | } 64 | resp, err := this.client.Do(req) 65 | if DEBUG { 66 | log.Println(time.Now().Sub(oldTime)) 67 | } 68 | respData, err := this.handleResponseContent(resp, err) 69 | return resp, respData, err 70 | } 71 | func (this *HttpClient) handleResponseContent(resp *http.Response, err error) ([]byte, error) { 72 | if DEBUG { 73 | dump, dumpErr := httputil.DumpResponse(resp, true) 74 | if dumpErr != nil { 75 | log.Println("error when dump response:", dumpErr) 76 | } 77 | log.Println("*** response dump ***") 78 | log.Println(string(dump)) 79 | } 80 | if err != nil { 81 | return nil, err 82 | } else { 83 | return readAllResponseBodyWithError(resp) 84 | } 85 | } 86 | 87 | func mergeResponseError(err error, resp *http.Response) error { 88 | if err != nil { 89 | return err 90 | } else if resp.StatusCode != http.StatusOK { 91 | return errors.New("request not ok, status: " + strconv.Itoa(resp.StatusCode) + 92 | ", body: " + string(readAllResponseBodyIgnoreError(resp))) 93 | } else { 94 | return nil 95 | } 96 | } 97 | 98 | func readAllResponseBodyIgnoreError(resp *http.Response) []byte { 99 | respData, _ := readAllResponseBodyWithError(resp) 100 | return respData 101 | } 102 | 103 | func readAllResponseBodyWithError(resp *http.Response) ([]byte, error) { 104 | // defer resp.Body.Close() 105 | respData, err := ioutil.ReadAll(resp.Body) 106 | if err != nil { 107 | log.Println(err) 108 | } 109 | return respData, err 110 | } 111 | -------------------------------------------------------------------------------- /object_test.go: -------------------------------------------------------------------------------- 1 | package bcsgo 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "strings" 7 | "testing" 8 | "time" 9 | ) 10 | 11 | var bucketForObjectTest *Bucket 12 | 13 | const ( 14 | _LARGER_NAME = "256KB.data" 15 | _TEST_NAME = "test.txt" 16 | ) 17 | 18 | func createTestFile(filename string, size int) { 19 | file, _ := os.Create(filename) 20 | file.WriteString(strings.Repeat(" ", size)) 21 | file.Close() 22 | } 23 | func deleteTestFile(filename string) { 24 | os.Remove(filename) 25 | } 26 | 27 | func TestObjectInit(t *testing.T) { 28 | bucket := createBucketTempForTest(t) 29 | bucketForObjectTest = bucket 30 | 31 | createTestFile(_LARGER_NAME, 256*1024) 32 | createTestFile(_TEST_NAME, 1024) 33 | } 34 | 35 | func TestObjectPutAndListAndHeadAndDeleteObject(t *testing.T) { 36 | bucket := bucketForObjectTest 37 | // todo file name with blank char 38 | path := "/testDir/testwithblank.txt" 39 | testObj := bucket.Object(path) 40 | testObj, err := testObj.PutFileWithACL(_TEST_NAME, ACL_PUBLIC_READ) 41 | if err != nil { 42 | t.Error(err) 43 | } 44 | if testObj.AbsolutePath != path { 45 | t.Error("testObj.AbsolutePath != path", testObj.AbsolutePath, path) 46 | } 47 | 48 | // expectedPublicLink := fmt.Sprintf("%s/%s%s", BCS_HOST, bucket.Name, path) 49 | // publicLink := testObj.PublicLink() 50 | // if expectedPublicLink != publicLink { 51 | // t.Error("expectedPublicLink != publicLink", expectedPublicLink, publicLink) 52 | // } 53 | 54 | headErr := testObj.Head() 55 | if headErr != nil { 56 | t.Error(headErr) 57 | } 58 | if testObj.ContentMD5 == "" || testObj.VersionKey == "" { 59 | t.Error("Info after HEAD is not ok!") 60 | } 61 | 62 | listObjectsTest := func(prefix string, start, limit, expectedCount int) { 63 | objects, e := bucket.ListObjects(prefix, start, limit) 64 | if e != nil { 65 | t.Error("object list shouldn't be nil") 66 | } 67 | for _, pObject := range objects.Objects { 68 | if pObject == nil { 69 | t.Error("object should not be nil") 70 | } 71 | } 72 | resultCount := len(objects.Objects) 73 | if expectedCount != resultCount { 74 | t.Error(fmt.Sprintf(`expectedCount != result, expectedCount = %d, resultCount = %d`, expectedCount, resultCount)) 75 | } 76 | } 77 | 78 | listObjectsTest("", 0, 100, 1) 79 | listObjectsTest("/", 1, 200, 0) 80 | listObjectsTest("/testDir/testwithblank.txt", 0, 1, 1) 81 | listObjectsTest("/testDir/testwithblank.txt!", 0, 2, 0) 82 | 83 | deleteErr := testObj.Delete() 84 | if deleteErr != nil { 85 | t.Error(deleteErr) 86 | } 87 | } 88 | 89 | func TestObjectLargerSingleFileAndACLAndCopy(t *testing.T) { 90 | bucket := bucketForObjectTest 91 | 92 | obj := bucket.Object("/larger.data") 93 | obj, err := obj.PutFile(_LARGER_NAME) 94 | if err != nil { 95 | t.Error(err) 96 | } 97 | 98 | acl, aclErr := obj.GetACL() 99 | if aclErr != nil { 100 | t.Error(aclErr) 101 | } 102 | if acl == "" { 103 | t.Error("acl string shouldn't be nil") 104 | } 105 | 106 | setACLCheckError := func(acl string) { 107 | putErr := obj.SetACL(acl) 108 | if putErr != nil { 109 | t.Error(putErr) 110 | } 111 | } 112 | 113 | setACLCheckError(ACL_PUBLIC_CONTROL) 114 | setACLCheckError(ACL_PUBLIC_READ) 115 | setACLCheckError(ACL_PUBLIC_WRITE) 116 | setACLCheckError(ACL_PUBLIC_READ_WRITE) 117 | setACLCheckError(ACL_PRIVATE) 118 | 119 | dupObject := bucket.Object("/larger2.data") 120 | dupObject, copyErr := obj.CopyTo(dupObject) 121 | if copyErr != nil { 122 | t.Error(copyErr) 123 | } 124 | if dupObject.Size != obj.Size { 125 | t.Error("object size after copy exists differences") 126 | t.Log(dupObject, obj) 127 | } 128 | // if dupObject.ContentMD5 != obj.ContentMD5 { 129 | // t.Error("object md5 after copy exists differences") 130 | // t.Log(dupObject, obj) 131 | // } 132 | 133 | deleteObject := func(obj *Object) { 134 | deleteErr := obj.Delete() 135 | if deleteErr != nil { 136 | t.Error(deleteErr) 137 | } 138 | } 139 | 140 | deleteObject(obj) 141 | deleteObject(dupObject) 142 | } 143 | 144 | func TestObjectFinalize(t *testing.T) { 145 | time.Sleep(500 * time.Millisecond) 146 | deleteBucketForTest(t, bucketForObjectTest) 147 | bucketForObjectTest = nil 148 | deleteTestFile(_LARGER_NAME) 149 | deleteTestFile(_TEST_NAME) 150 | } 151 | -------------------------------------------------------------------------------- /object.go: -------------------------------------------------------------------------------- 1 | package bcsgo 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "os" 7 | "strconv" 8 | ) 9 | 10 | type Object struct { 11 | bucket *Bucket 12 | VersionKey string `json:"version_key"` 13 | AbsolutePath string `json:"object"` 14 | Superfile string `json:"superfile"` 15 | Size int64 `json:"size,string"` 16 | ParentDir string `json:"parent_dir"` 17 | IsDir string `json:"is_dir"` 18 | MDatetime string `json:"mdatetime"` 19 | RefKey string `json:"ref_key"` 20 | ContentMD5 string `json:"content_md5"` 21 | } 22 | 23 | func (this *Object) getUrl() string { 24 | return this.bucket.bcs.restUrl(GET, this.bucket.Name, this.AbsolutePath) 25 | } 26 | func (this *Object) getACLUrl() string { 27 | return this.getUrl() + "&acl=1" 28 | } 29 | func (this *Object) putUrl() string { 30 | return this.bucket.bcs.restUrl(PUT, this.bucket.Name, this.AbsolutePath) 31 | } 32 | func (this *Object) putACLUrl() string { 33 | return this.putUrl() + "&acl=1" 34 | } 35 | func (this *Object) headUrl() string { 36 | return this.bucket.bcs.restUrl(HEAD, this.bucket.Name, this.AbsolutePath) 37 | } 38 | func (this *Object) deleteUrl() string { 39 | return this.bucket.bcs.restUrl(DELETE, this.bucket.Name, this.AbsolutePath) 40 | } 41 | func (this *Object) Link() string { 42 | return this.getUrl() 43 | } 44 | func (this *Object) PublicLink() string { 45 | return this.bucket.bcs.urlWithoutSign(this.bucket.Name, this.AbsolutePath) 46 | } 47 | func (this *Object) Head() error { 48 | link := this.headUrl() 49 | resp, _, err := this.bucket.bcs.httpClient.Head(link) 50 | err = mergeResponseError(err, resp) 51 | if err != nil { 52 | return err 53 | } else { 54 | this.Size = resp.ContentLength 55 | this.ContentMD5 = resp.Header.Get(HEADER_CONTENT_MD5) 56 | this.VersionKey = resp.Header.Get(HEADER_VERSION) 57 | return nil 58 | } 59 | } 60 | func (this *Object) PutFile(localFile string) (*Object, error) { 61 | return this.putFileInner(localFile, "") 62 | } 63 | func (this *Object) PutFileWithACL(localFile, acl string) (*Object, error) { 64 | return this.putFileInner(localFile, acl) 65 | } 66 | func (this *Object) putFileInner(localFile string, acl string) (*Object, error) { 67 | link := this.putUrl() 68 | file, err := os.Open(localFile) 69 | if err != nil { 70 | return nil, err 71 | } 72 | fileInfo, err := file.Stat() 73 | if err != nil { 74 | return nil, err 75 | } 76 | var modifyHeader func(header *http.Header) = nil 77 | if acl != "" { 78 | modifyHeader = func(header *http.Header) { 79 | header.Set(HEADER_ACL, acl) 80 | } 81 | } 82 | resp, _, err := this.bucket.bcs.httpClient.Put(link, file, fileInfo.Size(), modifyHeader) 83 | err = mergeResponseError(err, resp) 84 | if err != nil { 85 | return nil, err 86 | } else { 87 | this.ContentMD5 = resp.Header.Get(HEADER_CONTENT_MD5) 88 | this.VersionKey = resp.Header.Get(HEADER_VERSION) // TODO check version json and this 89 | this.Size, _ = strconv.ParseInt(resp.Header.Get(HEADER_FILESIZE), 10, 64) 90 | return this, err 91 | } 92 | } 93 | func (this *Object) Delete() error { 94 | link := this.deleteUrl() 95 | resp, _, err := this.bucket.bcs.httpClient.Delete(link) 96 | return mergeResponseError(err, resp) 97 | } 98 | func (this *Object) refStr() string { 99 | return fmt.Sprintf(`bs://%s%s`, this.bucket.Name, this.AbsolutePath) 100 | } 101 | func (this *Object) GetACL() (string, error) { 102 | link := this.getACLUrl() 103 | resp, data, err := this.bucket.bcs.httpClient.Get(link) 104 | err = mergeResponseError(err, resp) 105 | return string(data), err 106 | } 107 | func (this *Object) SetACL(acl string) error { 108 | link := this.putACLUrl() 109 | modifyHeader := func(header *http.Header) { 110 | header.Set(HEADER_ACL, acl) 111 | } 112 | resp, _, err := this.bucket.bcs.httpClient.Put(link, nil, 0, modifyHeader) 113 | return mergeResponseError(err, resp) 114 | } 115 | func (this *Object) CopyTo(target *Object) (*Object, error) { 116 | // take care of this, target put url 117 | link := target.putUrl() 118 | modifyHeader := func(header *http.Header) { 119 | header.Set(HEADER_COPY_SOURCE, this.refStr()) 120 | } 121 | resp, _, err := this.bucket.bcs.httpClient.Put(link, nil, 0, modifyHeader) 122 | err = mergeResponseError(err, resp) 123 | if err != nil { 124 | return nil, err 125 | } else { 126 | target.ContentMD5 = resp.Header.Get(HEADER_CONTENT_MD5) 127 | target.VersionKey = resp.Header.Get(HEADER_VERSION) // TODO check version json and this 128 | target.Size, _ = strconv.ParseInt(resp.Header.Get(HEADER_FILESIZE), 10, 64) 129 | return target, err 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | --------------------------------------------------------------------------------