conn.go 19 KB

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