conn.go 19 KB

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