conn.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. package oss
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "encoding/base64"
  6. "encoding/json"
  7. "encoding/xml"
  8. "fmt"
  9. "hash"
  10. "io"
  11. "io/ioutil"
  12. "net"
  13. "net/http"
  14. "net/url"
  15. "os"
  16. "sort"
  17. "strconv"
  18. "strings"
  19. "time"
  20. )
  21. // Conn defines OSS Conn
  22. type Conn struct {
  23. config *Config
  24. url *urlMaker
  25. client *http.Client
  26. }
  27. var signKeyList = []string{"acl", "uploads", "location", "cors", "logging", "website", "referer", "lifecycle", "delete", "append", "tagging", "objectMeta", "uploadId", "partNumber", "security-token", "position", "img", "style", "styleName", "replication", "replicationProgress", "replicationLocation", "cname", "bucketInfo", "comp", "qos", "live", "status", "vod", "startTime", "endTime", "symlink", "x-oss-process", "response-content-type", "response-content-language", "response-expires", "response-cache-control", "response-content-disposition", "response-content-encoding", "udf", "udfName", "udfImage", "udfId", "udfImageDesc", "udfApplication", "comp", "udfApplicationLog", "restore", "callback", "callback-var"}
  28. // init initializes Conn
  29. func (conn *Conn) init(config *Config, urlMaker *urlMaker, client *http.Client) error {
  30. if client == nil {
  31. // New transport
  32. transport := newTransport(conn, config)
  33. // Proxy
  34. if conn.config.IsUseProxy {
  35. proxyURL, err := url.Parse(config.ProxyHost)
  36. if err != nil {
  37. return err
  38. }
  39. transport.Proxy = http.ProxyURL(proxyURL)
  40. }
  41. client = &http.Client{Transport: transport}
  42. }
  43. conn.config = config
  44. conn.url = urlMaker
  45. conn.client = client
  46. return nil
  47. }
  48. // Do sends request and returns the response
  49. func (conn Conn) Do(method, bucketName, objectName string, params map[string]interface{}, headers map[string]string,
  50. data io.Reader, initCRC uint64, listener ProgressListener) (*Response, error) {
  51. urlParams := conn.getURLParams(params)
  52. subResource := conn.getSubResource(params)
  53. uri := conn.url.getURL(bucketName, objectName, urlParams)
  54. resource := conn.url.getResource(bucketName, objectName, subResource)
  55. return conn.doRequest(method, uri, resource, headers, data, initCRC, listener)
  56. }
  57. // DoURL sends the request with signed URL and returns the response result.
  58. func (conn Conn) DoURL(method HTTPMethod, signedURL string, headers map[string]string,
  59. data io.Reader, initCRC uint64, listener ProgressListener) (*Response, error) {
  60. // Get URI from signedURL
  61. uri, err := url.ParseRequestURI(signedURL)
  62. if err != nil {
  63. return nil, err
  64. }
  65. m := strings.ToUpper(string(method))
  66. req := &http.Request{
  67. Method: m,
  68. URL: uri,
  69. Proto: "HTTP/1.1",
  70. ProtoMajor: 1,
  71. ProtoMinor: 1,
  72. Header: make(http.Header),
  73. Host: uri.Host,
  74. }
  75. tracker := &readerTracker{completedBytes: 0}
  76. fd, crc := conn.handleBody(req, data, initCRC, listener, tracker)
  77. if fd != nil {
  78. defer func() {
  79. fd.Close()
  80. os.Remove(fd.Name())
  81. }()
  82. }
  83. if conn.config.IsAuthProxy {
  84. auth := conn.config.ProxyUser + ":" + conn.config.ProxyPassword
  85. basic := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
  86. req.Header.Set("Proxy-Authorization", basic)
  87. }
  88. req.Header.Set(HTTPHeaderHost, conn.config.Endpoint)
  89. req.Header.Set(HTTPHeaderUserAgent, conn.config.UserAgent)
  90. if headers != nil {
  91. for k, v := range headers {
  92. req.Header.Set(k, v)
  93. }
  94. }
  95. // Transfer started
  96. event := newProgressEvent(TransferStartedEvent, 0, req.ContentLength)
  97. publishProgress(listener, event)
  98. if conn.config.LogLevel >= Debug {
  99. conn.LoggerHttpReq(req)
  100. }
  101. resp, err := conn.client.Do(req)
  102. if err != nil {
  103. // Transfer failed
  104. event = newProgressEvent(TransferFailedEvent, tracker.completedBytes, req.ContentLength)
  105. publishProgress(listener, event)
  106. return nil, err
  107. }
  108. if conn.config.LogLevel >= Debug {
  109. //print out http resp
  110. conn.LoggerHttpResp(req, resp)
  111. }
  112. // Transfer completed
  113. event = newProgressEvent(TransferCompletedEvent, tracker.completedBytes, req.ContentLength)
  114. publishProgress(listener, event)
  115. return conn.handleResponse(resp, crc)
  116. }
  117. func (conn Conn) getURLParams(params map[string]interface{}) string {
  118. // Sort
  119. keys := make([]string, 0, len(params))
  120. for k := range params {
  121. keys = append(keys, k)
  122. }
  123. sort.Strings(keys)
  124. // Serialize
  125. var buf bytes.Buffer
  126. for _, k := range keys {
  127. if buf.Len() > 0 {
  128. buf.WriteByte('&')
  129. }
  130. buf.WriteString(url.QueryEscape(k))
  131. if params[k] != nil {
  132. buf.WriteString("=" + url.QueryEscape(params[k].(string)))
  133. }
  134. }
  135. return buf.String()
  136. }
  137. func (conn Conn) getSubResource(params map[string]interface{}) string {
  138. // Sort
  139. keys := make([]string, 0, len(params))
  140. for k := range params {
  141. if conn.isParamSign(k) {
  142. keys = append(keys, k)
  143. }
  144. }
  145. sort.Strings(keys)
  146. // Serialize
  147. var buf bytes.Buffer
  148. for _, k := range keys {
  149. if buf.Len() > 0 {
  150. buf.WriteByte('&')
  151. }
  152. buf.WriteString(k)
  153. if params[k] != nil {
  154. buf.WriteString("=" + params[k].(string))
  155. }
  156. }
  157. return buf.String()
  158. }
  159. func (conn Conn) isParamSign(paramKey string) bool {
  160. for _, k := range signKeyList {
  161. if paramKey == k {
  162. return true
  163. }
  164. }
  165. return false
  166. }
  167. func (conn Conn) doRequest(method string, uri *url.URL, canonicalizedResource string, headers map[string]string,
  168. data io.Reader, initCRC uint64, listener ProgressListener) (*Response, error) {
  169. method = strings.ToUpper(method)
  170. req := &http.Request{
  171. Method: method,
  172. URL: uri,
  173. Proto: "HTTP/1.1",
  174. ProtoMajor: 1,
  175. ProtoMinor: 1,
  176. Header: make(http.Header),
  177. Host: uri.Host,
  178. }
  179. tracker := &readerTracker{completedBytes: 0}
  180. fd, crc := conn.handleBody(req, data, initCRC, listener, tracker)
  181. if fd != nil {
  182. defer func() {
  183. fd.Close()
  184. os.Remove(fd.Name())
  185. }()
  186. }
  187. if conn.config.IsAuthProxy {
  188. auth := conn.config.ProxyUser + ":" + conn.config.ProxyPassword
  189. basic := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
  190. req.Header.Set("Proxy-Authorization", basic)
  191. }
  192. date := time.Now().UTC().Format(http.TimeFormat)
  193. req.Header.Set(HTTPHeaderDate, date)
  194. req.Header.Set(HTTPHeaderHost, conn.config.Endpoint)
  195. req.Header.Set(HTTPHeaderUserAgent, conn.config.UserAgent)
  196. if conn.config.SecurityToken != "" {
  197. req.Header.Set(HTTPHeaderOssSecurityToken, conn.config.SecurityToken)
  198. }
  199. if headers != nil {
  200. for k, v := range headers {
  201. req.Header.Set(k, v)
  202. }
  203. }
  204. conn.signHeader(req, canonicalizedResource)
  205. // Transfer started
  206. event := newProgressEvent(TransferStartedEvent, 0, req.ContentLength)
  207. publishProgress(listener, event)
  208. if conn.config.LogLevel >= Debug {
  209. conn.LoggerHttpReq(req)
  210. }
  211. resp, err := conn.client.Do(req)
  212. if err != nil {
  213. // Transfer failed
  214. event = newProgressEvent(TransferFailedEvent, tracker.completedBytes, req.ContentLength)
  215. publishProgress(listener, event)
  216. return nil, err
  217. }
  218. if conn.config.LogLevel >= Debug {
  219. //print out http resp
  220. conn.LoggerHttpResp(req, resp)
  221. }
  222. // Transfer completed
  223. event = newProgressEvent(TransferCompletedEvent, tracker.completedBytes, req.ContentLength)
  224. publishProgress(listener, event)
  225. return conn.handleResponse(resp, crc)
  226. }
  227. func (conn Conn) signURL(method HTTPMethod, bucketName, objectName string, expiration int64, params map[string]interface{}, headers map[string]string) string {
  228. if conn.config.SecurityToken != "" {
  229. params[HTTPParamSecurityToken] = conn.config.SecurityToken
  230. }
  231. subResource := conn.getSubResource(params)
  232. canonicalizedResource := conn.url.getResource(bucketName, objectName, subResource)
  233. m := strings.ToUpper(string(method))
  234. req := &http.Request{
  235. Method: m,
  236. Header: make(http.Header),
  237. }
  238. if conn.config.IsAuthProxy {
  239. auth := conn.config.ProxyUser + ":" + conn.config.ProxyPassword
  240. basic := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
  241. req.Header.Set("Proxy-Authorization", basic)
  242. }
  243. req.Header.Set(HTTPHeaderDate, strconv.FormatInt(expiration, 10))
  244. req.Header.Set(HTTPHeaderHost, conn.config.Endpoint)
  245. req.Header.Set(HTTPHeaderUserAgent, conn.config.UserAgent)
  246. if headers != nil {
  247. for k, v := range headers {
  248. req.Header.Set(k, v)
  249. }
  250. }
  251. signedStr := conn.getSignedStr(req, canonicalizedResource)
  252. params[HTTPParamExpires] = strconv.FormatInt(expiration, 10)
  253. params[HTTPParamAccessKeyID] = conn.config.AccessKeyID
  254. params[HTTPParamSignature] = signedStr
  255. urlParams := conn.getURLParams(params)
  256. return conn.url.getSignURL(bucketName, objectName, urlParams)
  257. }
  258. // handleBody handles request body
  259. func (conn Conn) handleBody(req *http.Request, body io.Reader, initCRC uint64,
  260. listener ProgressListener, tracker *readerTracker) (*os.File, hash.Hash64) {
  261. var file *os.File
  262. var crc hash.Hash64
  263. reader := body
  264. // Length
  265. switch v := body.(type) {
  266. case *bytes.Buffer:
  267. req.ContentLength = int64(v.Len())
  268. case *bytes.Reader:
  269. req.ContentLength = int64(v.Len())
  270. case *strings.Reader:
  271. req.ContentLength = int64(v.Len())
  272. case *os.File:
  273. req.ContentLength = tryGetFileSize(v)
  274. case *io.LimitedReader:
  275. req.ContentLength = int64(v.N)
  276. }
  277. req.Header.Set(HTTPHeaderContentLength, strconv.FormatInt(req.ContentLength, 10))
  278. // MD5
  279. if body != nil && conn.config.IsEnableMD5 && req.Header.Get(HTTPHeaderContentMD5) == "" {
  280. md5 := ""
  281. reader, md5, file, _ = calcMD5(body, req.ContentLength, conn.config.MD5Threshold)
  282. req.Header.Set(HTTPHeaderContentMD5, md5)
  283. }
  284. // CRC
  285. if reader != nil && conn.config.IsEnableCRC {
  286. crc = NewCRC(crcTable(), initCRC)
  287. reader = TeeReader(reader, crc, req.ContentLength, listener, tracker)
  288. }
  289. // HTTP body
  290. rc, ok := reader.(io.ReadCloser)
  291. if !ok && reader != nil {
  292. rc = ioutil.NopCloser(reader)
  293. }
  294. req.Body = rc
  295. return file, crc
  296. }
  297. func tryGetFileSize(f *os.File) int64 {
  298. fInfo, _ := f.Stat()
  299. return fInfo.Size()
  300. }
  301. // handleResponse handles response
  302. func (conn Conn) handleResponse(resp *http.Response, crc hash.Hash64) (*Response, error) {
  303. var cliCRC uint64
  304. var srvCRC uint64
  305. statusCode := resp.StatusCode
  306. if statusCode >= 400 && statusCode <= 505 {
  307. // 4xx and 5xx indicate that the operation has error occurred
  308. var respBody []byte
  309. respBody, err := readResponseBody(resp)
  310. if err != nil {
  311. return nil, err
  312. }
  313. if len(respBody) == 0 {
  314. err = ServiceError{
  315. StatusCode: statusCode,
  316. RequestID: resp.Header.Get(HTTPHeaderOssRequestID),
  317. }
  318. } else {
  319. // Response contains storage service error object, unmarshal
  320. srvErr, errIn := serviceErrFromXML(respBody, resp.StatusCode,
  321. resp.Header.Get(HTTPHeaderOssRequestID))
  322. if errIn != nil { // error unmarshaling the error response
  323. err = fmt.Errorf("oss: service returned invalid response body, status = %s, RequestId = %s", resp.Status, resp.Header.Get(HTTPHeaderOssRequestID))
  324. } else {
  325. err = srvErr
  326. }
  327. }
  328. return &Response{
  329. StatusCode: resp.StatusCode,
  330. Headers: resp.Header,
  331. Body: ioutil.NopCloser(bytes.NewReader(respBody)), // restore the body
  332. }, err
  333. } else if statusCode >= 300 && statusCode <= 307 {
  334. // OSS use 3xx, but response has no body
  335. err := fmt.Errorf("oss: service returned %d,%s", resp.StatusCode, resp.Status)
  336. return &Response{
  337. StatusCode: resp.StatusCode,
  338. Headers: resp.Header,
  339. Body: resp.Body,
  340. }, err
  341. }
  342. if conn.config.IsEnableCRC && crc != nil {
  343. cliCRC = crc.Sum64()
  344. }
  345. srvCRC, _ = strconv.ParseUint(resp.Header.Get(HTTPHeaderOssCRC64), 10, 64)
  346. // 2xx, successful
  347. return &Response{
  348. StatusCode: resp.StatusCode,
  349. Headers: resp.Header,
  350. Body: resp.Body,
  351. ClientCRC: cliCRC,
  352. ServerCRC: srvCRC,
  353. }, nil
  354. }
  355. func (conn Conn) LoggerHttpReq(req *http.Request) {
  356. var logBuffer bytes.Buffer
  357. logBuffer.WriteString(fmt.Sprintf("[Req:%p]Method:%s\t", req, req.Method))
  358. logBuffer.WriteString(fmt.Sprintf("Host:%s\t", req.URL.Host))
  359. logBuffer.WriteString(fmt.Sprintf("Path:%s\t", req.URL.Path))
  360. logBuffer.WriteString(fmt.Sprintf("Query:%s\t", req.URL.RawQuery))
  361. logBuffer.WriteString(fmt.Sprintf("Header info:"))
  362. for k, v := range req.Header {
  363. var valueBuffer bytes.Buffer
  364. for j := 0; j < len(v); j++ {
  365. if j > 0 {
  366. valueBuffer.WriteString(" ")
  367. }
  368. valueBuffer.WriteString(v[j])
  369. }
  370. logBuffer.WriteString(fmt.Sprintf("\t%s:%s", k, valueBuffer.String()))
  371. }
  372. conn.config.WriteLog(Debug, "%s\n", logBuffer.String())
  373. }
  374. func (conn Conn) LoggerHttpResp(req *http.Request, resp *http.Response) {
  375. var logBuffer bytes.Buffer
  376. logBuffer.WriteString(fmt.Sprintf("[Resp:%p]StatusCode:%d\t", req, resp.StatusCode))
  377. logBuffer.WriteString(fmt.Sprintf("Header info:"))
  378. for k, v := range resp.Header {
  379. var valueBuffer bytes.Buffer
  380. for j := 0; j < len(v); j++ {
  381. if j > 0 {
  382. valueBuffer.WriteString(" ")
  383. }
  384. valueBuffer.WriteString(v[j])
  385. }
  386. logBuffer.WriteString(fmt.Sprintf("\t%s:%s", k, valueBuffer.String()))
  387. }
  388. conn.config.WriteLog(Debug, "%s\n", logBuffer.String())
  389. }
  390. func calcMD5(body io.Reader, contentLen, md5Threshold int64) (reader io.Reader, b64 string, tempFile *os.File, err error) {
  391. if contentLen == 0 || contentLen > md5Threshold {
  392. // Huge body, use temporary file
  393. tempFile, err = ioutil.TempFile(os.TempDir(), TempFilePrefix)
  394. if tempFile != nil {
  395. io.Copy(tempFile, body)
  396. tempFile.Seek(0, os.SEEK_SET)
  397. md5 := md5.New()
  398. io.Copy(md5, tempFile)
  399. sum := md5.Sum(nil)
  400. b64 = base64.StdEncoding.EncodeToString(sum[:])
  401. tempFile.Seek(0, os.SEEK_SET)
  402. reader = tempFile
  403. }
  404. } else {
  405. // Small body, use memory
  406. buf, _ := ioutil.ReadAll(body)
  407. sum := md5.Sum(buf)
  408. b64 = base64.StdEncoding.EncodeToString(sum[:])
  409. reader = bytes.NewReader(buf)
  410. }
  411. return
  412. }
  413. func readResponseBody(resp *http.Response) ([]byte, error) {
  414. defer resp.Body.Close()
  415. out, err := ioutil.ReadAll(resp.Body)
  416. if err == io.EOF {
  417. err = nil
  418. }
  419. return out, err
  420. }
  421. func serviceErrFromXML(body []byte, statusCode int, requestID string) (ServiceError, error) {
  422. var storageErr ServiceError
  423. if err := xml.Unmarshal(body, &storageErr); err != nil {
  424. return storageErr, err
  425. }
  426. storageErr.StatusCode = statusCode
  427. storageErr.RequestID = requestID
  428. storageErr.RawMessage = string(body)
  429. return storageErr, nil
  430. }
  431. func xmlUnmarshal(body io.Reader, v interface{}) error {
  432. data, err := ioutil.ReadAll(body)
  433. if err != nil {
  434. return err
  435. }
  436. return xml.Unmarshal(data, v)
  437. }
  438. func jsonUnmarshal(body io.Reader, v interface{}) error {
  439. data, err := ioutil.ReadAll(body)
  440. if err != nil {
  441. return err
  442. }
  443. return json.Unmarshal(data, v)
  444. }
  445. // timeoutConn handles HTTP timeout
  446. type timeoutConn struct {
  447. conn net.Conn
  448. timeout time.Duration
  449. longTimeout time.Duration
  450. }
  451. func newTimeoutConn(conn net.Conn, timeout time.Duration, longTimeout time.Duration) *timeoutConn {
  452. conn.SetReadDeadline(time.Now().Add(longTimeout))
  453. return &timeoutConn{
  454. conn: conn,
  455. timeout: timeout,
  456. longTimeout: longTimeout,
  457. }
  458. }
  459. func (c *timeoutConn) Read(b []byte) (n int, err error) {
  460. c.SetReadDeadline(time.Now().Add(c.timeout))
  461. n, err = c.conn.Read(b)
  462. c.SetReadDeadline(time.Now().Add(c.longTimeout))
  463. return n, err
  464. }
  465. func (c *timeoutConn) Write(b []byte) (n int, err error) {
  466. c.SetWriteDeadline(time.Now().Add(c.timeout))
  467. n, err = c.conn.Write(b)
  468. c.SetReadDeadline(time.Now().Add(c.longTimeout))
  469. return n, err
  470. }
  471. func (c *timeoutConn) Close() error {
  472. return c.conn.Close()
  473. }
  474. func (c *timeoutConn) LocalAddr() net.Addr {
  475. return c.conn.LocalAddr()
  476. }
  477. func (c *timeoutConn) RemoteAddr() net.Addr {
  478. return c.conn.RemoteAddr()
  479. }
  480. func (c *timeoutConn) SetDeadline(t time.Time) error {
  481. return c.conn.SetDeadline(t)
  482. }
  483. func (c *timeoutConn) SetReadDeadline(t time.Time) error {
  484. return c.conn.SetReadDeadline(t)
  485. }
  486. func (c *timeoutConn) SetWriteDeadline(t time.Time) error {
  487. return c.conn.SetWriteDeadline(t)
  488. }
  489. // UrlMaker builds URL and resource
  490. const (
  491. urlTypeCname = 1
  492. urlTypeIP = 2
  493. urlTypeAliyun = 3
  494. )
  495. type urlMaker struct {
  496. Scheme string // HTTP or HTTPS
  497. NetLoc string // Host or IP
  498. Type int // 1 CNAME, 2 IP, 3 ALIYUN
  499. IsProxy bool // Proxy
  500. }
  501. // Init parses endpoint
  502. func (um *urlMaker) Init(endpoint string, isCname bool, isProxy bool) {
  503. if strings.HasPrefix(endpoint, "http://") {
  504. um.Scheme = "http"
  505. um.NetLoc = endpoint[len("http://"):]
  506. } else if strings.HasPrefix(endpoint, "https://") {
  507. um.Scheme = "https"
  508. um.NetLoc = endpoint[len("https://"):]
  509. } else {
  510. um.Scheme = "http"
  511. um.NetLoc = endpoint
  512. }
  513. host, _, err := net.SplitHostPort(um.NetLoc)
  514. if err != nil {
  515. host = um.NetLoc
  516. if host[0] == '[' && host[len(host)-1] == ']' {
  517. host = host[1 : len(host)-1]
  518. }
  519. }
  520. ip := net.ParseIP(host)
  521. if ip != nil {
  522. um.Type = urlTypeIP
  523. } else if isCname {
  524. um.Type = urlTypeCname
  525. } else {
  526. um.Type = urlTypeAliyun
  527. }
  528. um.IsProxy = isProxy
  529. }
  530. // getURL gets URL
  531. func (um urlMaker) getURL(bucket, object, params string) *url.URL {
  532. host, path := um.buildURL(bucket, object)
  533. addr := ""
  534. if params == "" {
  535. addr = fmt.Sprintf("%s://%s%s", um.Scheme, host, path)
  536. } else {
  537. addr = fmt.Sprintf("%s://%s%s?%s", um.Scheme, host, path, params)
  538. }
  539. uri, _ := url.ParseRequestURI(addr)
  540. return uri
  541. }
  542. // getSignURL gets sign URL
  543. func (um urlMaker) getSignURL(bucket, object, params string) string {
  544. host, path := um.buildURL(bucket, object)
  545. return fmt.Sprintf("%s://%s%s?%s", um.Scheme, host, path, params)
  546. }
  547. // buildURL builds URL
  548. func (um urlMaker) buildURL(bucket, object string) (string, string) {
  549. var host = ""
  550. var path = ""
  551. object = url.QueryEscape(object)
  552. object = strings.Replace(object, "+", "%20", -1)
  553. if um.Type == urlTypeCname {
  554. host = um.NetLoc
  555. path = "/" + object
  556. } else if um.Type == urlTypeIP {
  557. if bucket == "" {
  558. host = um.NetLoc
  559. path = "/"
  560. } else {
  561. host = um.NetLoc
  562. path = fmt.Sprintf("/%s/%s", bucket, object)
  563. }
  564. } else {
  565. if bucket == "" {
  566. host = um.NetLoc
  567. path = "/"
  568. } else {
  569. host = bucket + "." + um.NetLoc
  570. path = "/" + object
  571. }
  572. }
  573. return host, path
  574. }
  575. // getResource gets canonicalized resource
  576. func (um urlMaker) getResource(bucketName, objectName, subResource string) string {
  577. if subResource != "" {
  578. subResource = "?" + subResource
  579. }
  580. if bucketName == "" {
  581. return fmt.Sprintf("/%s%s", bucketName, subResource)
  582. }
  583. return fmt.Sprintf("/%s/%s%s", bucketName, objectName, subResource)
  584. }