conn.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  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. func (conn Conn) signRtmpURL(bucketName, channelName, playlistName string, expiration int64) string {
  259. params := map[string]interface{}{}
  260. if playlistName != "" {
  261. params[HTTPParamPlaylistName] = playlistName
  262. }
  263. expireStr := strconv.FormatInt(expiration, 10)
  264. params[HTTPParamExpires] = expireStr
  265. if conn.config.AccessKeyID != "" {
  266. params[HTTPParamAccessKeyID] = conn.config.AccessKeyID
  267. if conn.config.SecurityToken != "" {
  268. params[HTTPParamSecurityToken] = conn.config.SecurityToken
  269. }
  270. signedStr := conn.getRtmpSignedStr(bucketName, channelName, playlistName, expiration, params)
  271. params[HTTPParamSignature] = signedStr
  272. }
  273. urlParams := conn.getURLParams(params)
  274. return conn.url.getSignRtmpURL(bucketName, channelName, urlParams)
  275. }
  276. // handleBody handles request body
  277. func (conn Conn) handleBody(req *http.Request, body io.Reader, initCRC uint64,
  278. listener ProgressListener, tracker *readerTracker) (*os.File, hash.Hash64) {
  279. var file *os.File
  280. var crc hash.Hash64
  281. reader := body
  282. // Length
  283. switch v := body.(type) {
  284. case *bytes.Buffer:
  285. req.ContentLength = int64(v.Len())
  286. case *bytes.Reader:
  287. req.ContentLength = int64(v.Len())
  288. case *strings.Reader:
  289. req.ContentLength = int64(v.Len())
  290. case *os.File:
  291. req.ContentLength = tryGetFileSize(v)
  292. case *io.LimitedReader:
  293. req.ContentLength = int64(v.N)
  294. }
  295. req.Header.Set(HTTPHeaderContentLength, strconv.FormatInt(req.ContentLength, 10))
  296. // MD5
  297. if body != nil && conn.config.IsEnableMD5 && req.Header.Get(HTTPHeaderContentMD5) == "" {
  298. md5 := ""
  299. reader, md5, file, _ = calcMD5(body, req.ContentLength, conn.config.MD5Threshold)
  300. req.Header.Set(HTTPHeaderContentMD5, md5)
  301. }
  302. // CRC
  303. if reader != nil && conn.config.IsEnableCRC {
  304. crc = NewCRC(crcTable(), initCRC)
  305. reader = TeeReader(reader, crc, req.ContentLength, listener, tracker)
  306. }
  307. // HTTP body
  308. rc, ok := reader.(io.ReadCloser)
  309. if !ok && reader != nil {
  310. rc = ioutil.NopCloser(reader)
  311. }
  312. req.Body = rc
  313. return file, crc
  314. }
  315. func tryGetFileSize(f *os.File) int64 {
  316. fInfo, _ := f.Stat()
  317. return fInfo.Size()
  318. }
  319. // handleResponse handles response
  320. func (conn Conn) handleResponse(resp *http.Response, crc hash.Hash64) (*Response, error) {
  321. var cliCRC uint64
  322. var srvCRC uint64
  323. statusCode := resp.StatusCode
  324. if statusCode >= 400 && statusCode <= 505 {
  325. // 4xx and 5xx indicate that the operation has error occurred
  326. var respBody []byte
  327. respBody, err := readResponseBody(resp)
  328. if err != nil {
  329. return nil, err
  330. }
  331. if len(respBody) == 0 {
  332. err = ServiceError{
  333. StatusCode: statusCode,
  334. RequestID: resp.Header.Get(HTTPHeaderOssRequestID),
  335. }
  336. } else {
  337. // Response contains storage service error object, unmarshal
  338. srvErr, errIn := serviceErrFromXML(respBody, resp.StatusCode,
  339. resp.Header.Get(HTTPHeaderOssRequestID))
  340. if errIn != nil { // error unmarshaling the error response
  341. err = fmt.Errorf("oss: service returned invalid response body, status = %s, RequestId = %s", resp.Status, resp.Header.Get(HTTPHeaderOssRequestID))
  342. } else {
  343. err = srvErr
  344. }
  345. }
  346. return &Response{
  347. StatusCode: resp.StatusCode,
  348. Headers: resp.Header,
  349. Body: ioutil.NopCloser(bytes.NewReader(respBody)), // restore the body
  350. }, err
  351. } else if statusCode >= 300 && statusCode <= 307 {
  352. // OSS use 3xx, but response has no body
  353. err := fmt.Errorf("oss: service returned %d,%s", resp.StatusCode, resp.Status)
  354. return &Response{
  355. StatusCode: resp.StatusCode,
  356. Headers: resp.Header,
  357. Body: resp.Body,
  358. }, err
  359. }
  360. if conn.config.IsEnableCRC && crc != nil {
  361. cliCRC = crc.Sum64()
  362. }
  363. srvCRC, _ = strconv.ParseUint(resp.Header.Get(HTTPHeaderOssCRC64), 10, 64)
  364. // 2xx, successful
  365. return &Response{
  366. StatusCode: resp.StatusCode,
  367. Headers: resp.Header,
  368. Body: resp.Body,
  369. ClientCRC: cliCRC,
  370. ServerCRC: srvCRC,
  371. }, nil
  372. }
  373. func (conn Conn) LoggerHttpReq(req *http.Request) {
  374. var logBuffer bytes.Buffer
  375. logBuffer.WriteString(fmt.Sprintf("[Req:%p]Method:%s\t", req, req.Method))
  376. logBuffer.WriteString(fmt.Sprintf("Host:%s\t", req.URL.Host))
  377. logBuffer.WriteString(fmt.Sprintf("Path:%s\t", req.URL.Path))
  378. logBuffer.WriteString(fmt.Sprintf("Query:%s\t", req.URL.RawQuery))
  379. logBuffer.WriteString(fmt.Sprintf("Header info:"))
  380. for k, v := range req.Header {
  381. var valueBuffer bytes.Buffer
  382. for j := 0; j < len(v); j++ {
  383. if j > 0 {
  384. valueBuffer.WriteString(" ")
  385. }
  386. valueBuffer.WriteString(v[j])
  387. }
  388. logBuffer.WriteString(fmt.Sprintf("\t%s:%s", k, valueBuffer.String()))
  389. }
  390. conn.config.WriteLog(Debug, "%s\n", logBuffer.String())
  391. }
  392. func (conn Conn) LoggerHttpResp(req *http.Request, resp *http.Response) {
  393. var logBuffer bytes.Buffer
  394. logBuffer.WriteString(fmt.Sprintf("[Resp:%p]StatusCode:%d\t", req, resp.StatusCode))
  395. logBuffer.WriteString(fmt.Sprintf("Header info:"))
  396. for k, v := range resp.Header {
  397. var valueBuffer bytes.Buffer
  398. for j := 0; j < len(v); j++ {
  399. if j > 0 {
  400. valueBuffer.WriteString(" ")
  401. }
  402. valueBuffer.WriteString(v[j])
  403. }
  404. logBuffer.WriteString(fmt.Sprintf("\t%s:%s", k, valueBuffer.String()))
  405. }
  406. conn.config.WriteLog(Debug, "%s\n", logBuffer.String())
  407. }
  408. func calcMD5(body io.Reader, contentLen, md5Threshold int64) (reader io.Reader, b64 string, tempFile *os.File, err error) {
  409. if contentLen == 0 || contentLen > md5Threshold {
  410. // Huge body, use temporary file
  411. tempFile, err = ioutil.TempFile(os.TempDir(), TempFilePrefix)
  412. if tempFile != nil {
  413. io.Copy(tempFile, body)
  414. tempFile.Seek(0, os.SEEK_SET)
  415. md5 := md5.New()
  416. io.Copy(md5, tempFile)
  417. sum := md5.Sum(nil)
  418. b64 = base64.StdEncoding.EncodeToString(sum[:])
  419. tempFile.Seek(0, os.SEEK_SET)
  420. reader = tempFile
  421. }
  422. } else {
  423. // Small body, use memory
  424. buf, _ := ioutil.ReadAll(body)
  425. sum := md5.Sum(buf)
  426. b64 = base64.StdEncoding.EncodeToString(sum[:])
  427. reader = bytes.NewReader(buf)
  428. }
  429. return
  430. }
  431. func readResponseBody(resp *http.Response) ([]byte, error) {
  432. defer resp.Body.Close()
  433. out, err := ioutil.ReadAll(resp.Body)
  434. if err == io.EOF {
  435. err = nil
  436. }
  437. return out, err
  438. }
  439. func serviceErrFromXML(body []byte, statusCode int, requestID string) (ServiceError, error) {
  440. var storageErr ServiceError
  441. if err := xml.Unmarshal(body, &storageErr); err != nil {
  442. return storageErr, err
  443. }
  444. storageErr.StatusCode = statusCode
  445. storageErr.RequestID = requestID
  446. storageErr.RawMessage = string(body)
  447. return storageErr, nil
  448. }
  449. func xmlUnmarshal(body io.Reader, v interface{}) error {
  450. data, err := ioutil.ReadAll(body)
  451. if err != nil {
  452. return err
  453. }
  454. return xml.Unmarshal(data, v)
  455. }
  456. func jsonUnmarshal(body io.Reader, v interface{}) error {
  457. data, err := ioutil.ReadAll(body)
  458. if err != nil {
  459. return err
  460. }
  461. return json.Unmarshal(data, v)
  462. }
  463. // timeoutConn handles HTTP timeout
  464. type timeoutConn struct {
  465. conn net.Conn
  466. timeout time.Duration
  467. longTimeout time.Duration
  468. }
  469. func newTimeoutConn(conn net.Conn, timeout time.Duration, longTimeout time.Duration) *timeoutConn {
  470. conn.SetReadDeadline(time.Now().Add(longTimeout))
  471. return &timeoutConn{
  472. conn: conn,
  473. timeout: timeout,
  474. longTimeout: longTimeout,
  475. }
  476. }
  477. func (c *timeoutConn) Read(b []byte) (n int, err error) {
  478. c.SetReadDeadline(time.Now().Add(c.timeout))
  479. n, err = c.conn.Read(b)
  480. c.SetReadDeadline(time.Now().Add(c.longTimeout))
  481. return n, err
  482. }
  483. func (c *timeoutConn) Write(b []byte) (n int, err error) {
  484. c.SetWriteDeadline(time.Now().Add(c.timeout))
  485. n, err = c.conn.Write(b)
  486. c.SetReadDeadline(time.Now().Add(c.longTimeout))
  487. return n, err
  488. }
  489. func (c *timeoutConn) Close() error {
  490. return c.conn.Close()
  491. }
  492. func (c *timeoutConn) LocalAddr() net.Addr {
  493. return c.conn.LocalAddr()
  494. }
  495. func (c *timeoutConn) RemoteAddr() net.Addr {
  496. return c.conn.RemoteAddr()
  497. }
  498. func (c *timeoutConn) SetDeadline(t time.Time) error {
  499. return c.conn.SetDeadline(t)
  500. }
  501. func (c *timeoutConn) SetReadDeadline(t time.Time) error {
  502. return c.conn.SetReadDeadline(t)
  503. }
  504. func (c *timeoutConn) SetWriteDeadline(t time.Time) error {
  505. return c.conn.SetWriteDeadline(t)
  506. }
  507. // UrlMaker builds URL and resource
  508. const (
  509. urlTypeCname = 1
  510. urlTypeIP = 2
  511. urlTypeAliyun = 3
  512. )
  513. type urlMaker struct {
  514. Scheme string // HTTP or HTTPS
  515. NetLoc string // Host or IP
  516. Type int // 1 CNAME, 2 IP, 3 ALIYUN
  517. IsProxy bool // Proxy
  518. }
  519. // Init parses endpoint
  520. func (um *urlMaker) Init(endpoint string, isCname bool, isProxy bool) {
  521. if strings.HasPrefix(endpoint, "http://") {
  522. um.Scheme = "http"
  523. um.NetLoc = endpoint[len("http://"):]
  524. } else if strings.HasPrefix(endpoint, "https://") {
  525. um.Scheme = "https"
  526. um.NetLoc = endpoint[len("https://"):]
  527. } else {
  528. um.Scheme = "http"
  529. um.NetLoc = endpoint
  530. }
  531. host, _, err := net.SplitHostPort(um.NetLoc)
  532. if err != nil {
  533. host = um.NetLoc
  534. if host[0] == '[' && host[len(host)-1] == ']' {
  535. host = host[1 : len(host)-1]
  536. }
  537. }
  538. ip := net.ParseIP(host)
  539. if ip != nil {
  540. um.Type = urlTypeIP
  541. } else if isCname {
  542. um.Type = urlTypeCname
  543. } else {
  544. um.Type = urlTypeAliyun
  545. }
  546. um.IsProxy = isProxy
  547. }
  548. // getURL gets URL
  549. func (um urlMaker) getURL(bucket, object, params string) *url.URL {
  550. host, path := um.buildURL(bucket, object)
  551. addr := ""
  552. if params == "" {
  553. addr = fmt.Sprintf("%s://%s%s", um.Scheme, host, path)
  554. } else {
  555. addr = fmt.Sprintf("%s://%s%s?%s", um.Scheme, host, path, params)
  556. }
  557. uri, _ := url.ParseRequestURI(addr)
  558. return uri
  559. }
  560. // getSignURL gets sign URL
  561. func (um urlMaker) getSignURL(bucket, object, params string) string {
  562. host, path := um.buildURL(bucket, object)
  563. return fmt.Sprintf("%s://%s%s?%s", um.Scheme, host, path, params)
  564. }
  565. // getSignRtmpURL Build Sign Rtmp URL
  566. func (um urlMaker) getSignRtmpURL(bucket, channelName, params string) string {
  567. host, path := um.buildURL(bucket, "live")
  568. channelName = url.QueryEscape(channelName)
  569. channelName = strings.Replace(channelName, "+", "%20", -1)
  570. return fmt.Sprintf("rtmp://%s%s/%s?%s", host, path, channelName, params)
  571. }
  572. // buildURL builds URL
  573. func (um urlMaker) buildURL(bucket, object string) (string, string) {
  574. var host = ""
  575. var path = ""
  576. object = url.QueryEscape(object)
  577. object = strings.Replace(object, "+", "%20", -1)
  578. if um.Type == urlTypeCname {
  579. host = um.NetLoc
  580. path = "/" + object
  581. } else if um.Type == urlTypeIP {
  582. if bucket == "" {
  583. host = um.NetLoc
  584. path = "/"
  585. } else {
  586. host = um.NetLoc
  587. path = fmt.Sprintf("/%s/%s", bucket, object)
  588. }
  589. } else {
  590. if bucket == "" {
  591. host = um.NetLoc
  592. path = "/"
  593. } else {
  594. host = bucket + "." + um.NetLoc
  595. path = "/" + object
  596. }
  597. }
  598. return host, path
  599. }
  600. // getResource gets canonicalized resource
  601. func (um urlMaker) getResource(bucketName, objectName, subResource string) string {
  602. if subResource != "" {
  603. subResource = "?" + subResource
  604. }
  605. if bucketName == "" {
  606. return fmt.Sprintf("/%s%s", bucketName, subResource)
  607. }
  608. return fmt.Sprintf("/%s/%s%s", bucketName, objectName, subResource)
  609. }