conn.go 19 KB

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