You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1412 lines
42 KiB

  1. // OAuth 1.0 consumer implementation.
  2. // See http://www.oauth.net and RFC 5849
  3. //
  4. // There are typically three parties involved in an OAuth exchange:
  5. // (1) The "Service Provider" (e.g. Google, Twitter, NetFlix) who operates the
  6. // service where the data resides.
  7. // (2) The "End User" who owns that data, and wants to grant access to a third-party.
  8. // (3) That third-party who wants access to the data (after first being authorized by
  9. // the user). This third-party is referred to as the "Consumer" in OAuth
  10. // terminology.
  11. //
  12. // This library is designed to help implement the third-party consumer by handling the
  13. // low-level authentication tasks, and allowing for authenticated requests to the
  14. // service provider on behalf of the user.
  15. //
  16. // Caveats:
  17. // - Currently only supports HMAC and RSA signatures.
  18. // - Currently only supports SHA1 and SHA256 hashes.
  19. // - Currently only supports OAuth 1.0
  20. //
  21. // Overview of how to use this library:
  22. // (1) First create a new Consumer instance with the NewConsumer function
  23. // (2) Get a RequestToken, and "authorization url" from GetRequestTokenAndUrl()
  24. // (3) Save the RequestToken, you will need it again in step 6.
  25. // (4) Redirect the user to the "authorization url" from step 2, where they will
  26. // authorize your access to the service provider.
  27. // (5) Wait. You will be called back on the CallbackUrl that you provide, and you
  28. // will recieve a "verification code".
  29. // (6) Call AuthorizeToken() with the RequestToken from step 2 and the
  30. // "verification code" from step 5.
  31. // (7) You will get back an AccessToken. Save this for as long as you need access
  32. // to the user's data, and treat it like a password; it is a secret.
  33. // (8) You can now throw away the RequestToken from step 2, it is no longer
  34. // necessary.
  35. // (9) Call "MakeHttpClient" using the AccessToken from step 7 to get an
  36. // HTTP client which can access protected resources.
  37. package oauth
  38. import (
  39. "bytes"
  40. "crypto"
  41. "crypto/hmac"
  42. cryptoRand "crypto/rand"
  43. "crypto/rsa"
  44. "encoding/base64"
  45. "errors"
  46. "fmt"
  47. "io"
  48. "io/ioutil"
  49. "math/rand"
  50. "mime/multipart"
  51. "net/http"
  52. "net/url"
  53. "sort"
  54. "strconv"
  55. "strings"
  56. "sync"
  57. "time"
  58. )
  59. const (
  60. OAUTH_VERSION = "1.0"
  61. SIGNATURE_METHOD_HMAC = "HMAC-"
  62. SIGNATURE_METHOD_RSA = "RSA-"
  63. HTTP_AUTH_HEADER = "Authorization"
  64. OAUTH_HEADER = "OAuth "
  65. BODY_HASH_PARAM = "oauth_body_hash"
  66. CALLBACK_PARAM = "oauth_callback"
  67. CONSUMER_KEY_PARAM = "oauth_consumer_key"
  68. NONCE_PARAM = "oauth_nonce"
  69. SESSION_HANDLE_PARAM = "oauth_session_handle"
  70. SIGNATURE_METHOD_PARAM = "oauth_signature_method"
  71. SIGNATURE_PARAM = "oauth_signature"
  72. TIMESTAMP_PARAM = "oauth_timestamp"
  73. TOKEN_PARAM = "oauth_token"
  74. TOKEN_SECRET_PARAM = "oauth_token_secret"
  75. VERIFIER_PARAM = "oauth_verifier"
  76. VERSION_PARAM = "oauth_version"
  77. )
  78. var HASH_METHOD_MAP = map[crypto.Hash]string{
  79. crypto.SHA1: "SHA1",
  80. crypto.SHA256: "SHA256",
  81. }
  82. // TODO(mrjones) Do we definitely want separate "Request" and "Access" token classes?
  83. // They're identical structurally, but used for different purposes.
  84. type RequestToken struct {
  85. Token string
  86. Secret string
  87. }
  88. type AccessToken struct {
  89. Token string
  90. Secret string
  91. AdditionalData map[string]string
  92. }
  93. type DataLocation int
  94. const (
  95. LOC_BODY DataLocation = iota + 1
  96. LOC_URL
  97. LOC_MULTIPART
  98. LOC_JSON
  99. LOC_XML
  100. )
  101. // Information about how to contact the service provider (see #1 above).
  102. // You usually find all of these URLs by reading the documentation for the service
  103. // that you're trying to connect to.
  104. // Some common examples are:
  105. // (1) Google, standard APIs:
  106. // http://code.google.com/apis/accounts/docs/OAuth_ref.html
  107. // - RequestTokenUrl: https://www.google.com/accounts/OAuthGetRequestToken
  108. // - AuthorizeTokenUrl: https://www.google.com/accounts/OAuthAuthorizeToken
  109. // - AccessTokenUrl: https://www.google.com/accounts/OAuthGetAccessToken
  110. // Note: Some Google APIs (for example, Google Latitude) use different values for
  111. // one or more of those URLs.
  112. // (2) Twitter API:
  113. // http://dev.twitter.com/pages/auth
  114. // - RequestTokenUrl: http://api.twitter.com/oauth/request_token
  115. // - AuthorizeTokenUrl: https://api.twitter.com/oauth/authorize
  116. // - AccessTokenUrl: https://api.twitter.com/oauth/access_token
  117. // (3) NetFlix API:
  118. // http://developer.netflix.com/docs/Security
  119. // - RequestTokenUrl: http://api.netflix.com/oauth/request_token
  120. // - AuthroizeTokenUrl: https://api-user.netflix.com/oauth/login
  121. // - AccessTokenUrl: http://api.netflix.com/oauth/access_token
  122. // Set HttpMethod if the service provider requires a different HTTP method
  123. // to be used for OAuth token requests
  124. type ServiceProvider struct {
  125. RequestTokenUrl string
  126. AuthorizeTokenUrl string
  127. AccessTokenUrl string
  128. HttpMethod string
  129. BodyHash bool
  130. IgnoreTimestamp bool
  131. // Enables non spec-compliant behavior:
  132. // Allow parameters to be passed in the query string rather
  133. // than the body.
  134. // See https://github.com/mrjones/oauth/pull/63
  135. SignQueryParams bool
  136. }
  137. func (sp *ServiceProvider) httpMethod() string {
  138. if sp.HttpMethod != "" {
  139. return sp.HttpMethod
  140. }
  141. return "GET"
  142. }
  143. // lockedNonceGenerator wraps a non-reentrant random number generator with a
  144. // lock
  145. type lockedNonceGenerator struct {
  146. nonceGenerator nonceGenerator
  147. lock sync.Mutex
  148. }
  149. func newLockedNonceGenerator(c clock) *lockedNonceGenerator {
  150. return &lockedNonceGenerator{
  151. nonceGenerator: rand.New(rand.NewSource(c.Nanos())),
  152. }
  153. }
  154. func (n *lockedNonceGenerator) Int63() int64 {
  155. n.lock.Lock()
  156. r := n.nonceGenerator.Int63()
  157. n.lock.Unlock()
  158. return r
  159. }
  160. // Consumers are stateless, you can call the various methods (GetRequestTokenAndUrl,
  161. // AuthorizeToken, and Get) on various different instances of Consumers *as long as
  162. // they were set up in the same way.* It is up to you, as the caller to persist the
  163. // necessary state (RequestTokens and AccessTokens).
  164. type Consumer struct {
  165. // Some ServiceProviders require extra parameters to be passed for various reasons.
  166. // For example Google APIs require you to set a scope= parameter to specify how much
  167. // access is being granted. The proper values for scope= depend on the service:
  168. // For more, see: http://code.google.com/apis/accounts/docs/OAuth.html#prepScope
  169. AdditionalParams map[string]string
  170. // The rest of this class is configured via the NewConsumer function.
  171. consumerKey string
  172. serviceProvider ServiceProvider
  173. // Some APIs (e.g. Netflix) aren't quite standard OAuth, and require passing
  174. // additional parameters when authorizing the request token. For most APIs
  175. // this field can be ignored. For Netflix, do something like:
  176. // consumer.AdditionalAuthorizationUrlParams = map[string]string{
  177. // "application_name": "YourAppName",
  178. // "oauth_consumer_key": "YourConsumerKey",
  179. // }
  180. AdditionalAuthorizationUrlParams map[string]string
  181. debug bool
  182. // Defaults to http.Client{}, can be overridden (e.g. for testing) as necessary
  183. HttpClient HttpClient
  184. // Some APIs (e.g. Intuit/Quickbooks) require sending additional headers along with
  185. // requests. (like "Accept" to specify the response type as XML or JSON) Note that this
  186. // will only *add* headers, not set existing ones.
  187. AdditionalHeaders map[string][]string
  188. // Private seams for mocking dependencies when testing
  189. clock clock
  190. // Seeded generators are not reentrant
  191. nonceGenerator nonceGenerator
  192. signer signer
  193. }
  194. func newConsumer(consumerKey string, serviceProvider ServiceProvider, httpClient *http.Client) *Consumer {
  195. clock := &defaultClock{}
  196. if httpClient == nil {
  197. httpClient = &http.Client{}
  198. }
  199. return &Consumer{
  200. consumerKey: consumerKey,
  201. serviceProvider: serviceProvider,
  202. clock: clock,
  203. HttpClient: httpClient,
  204. nonceGenerator: newLockedNonceGenerator(clock),
  205. AdditionalParams: make(map[string]string),
  206. AdditionalAuthorizationUrlParams: make(map[string]string),
  207. }
  208. }
  209. // Creates a new Consumer instance, with a HMAC-SHA1 signer
  210. // - consumerKey and consumerSecret:
  211. // values you should obtain from the ServiceProvider when you register your
  212. // application.
  213. //
  214. // - serviceProvider:
  215. // see the documentation for ServiceProvider for how to create this.
  216. //
  217. func NewConsumer(consumerKey string, consumerSecret string,
  218. serviceProvider ServiceProvider) *Consumer {
  219. consumer := newConsumer(consumerKey, serviceProvider, nil)
  220. consumer.signer = &HMACSigner{
  221. consumerSecret: consumerSecret,
  222. hashFunc: crypto.SHA1,
  223. }
  224. return consumer
  225. }
  226. // Creates a new Consumer instance, with a HMAC-SHA1 signer
  227. // - consumerKey and consumerSecret:
  228. // values you should obtain from the ServiceProvider when you register your
  229. // application.
  230. //
  231. // - serviceProvider:
  232. // see the documentation for ServiceProvider for how to create this.
  233. //
  234. // - httpClient:
  235. // Provides a custom implementation of the httpClient used under the hood
  236. // to make the request. This is especially useful if you want to use
  237. // Google App Engine.
  238. //
  239. func NewCustomHttpClientConsumer(consumerKey string, consumerSecret string,
  240. serviceProvider ServiceProvider, httpClient *http.Client) *Consumer {
  241. consumer := newConsumer(consumerKey, serviceProvider, httpClient)
  242. consumer.signer = &HMACSigner{
  243. consumerSecret: consumerSecret,
  244. hashFunc: crypto.SHA1,
  245. }
  246. return consumer
  247. }
  248. // Creates a new Consumer instance, with a HMAC signer
  249. // - consumerKey and consumerSecret:
  250. // values you should obtain from the ServiceProvider when you register your
  251. // application.
  252. //
  253. // - hashFunc:
  254. // the crypto.Hash to use for signatures
  255. //
  256. // - serviceProvider:
  257. // see the documentation for ServiceProvider for how to create this.
  258. //
  259. // - httpClient:
  260. // Provides a custom implementation of the httpClient used under the hood
  261. // to make the request. This is especially useful if you want to use
  262. // Google App Engine. Can be nil for default.
  263. //
  264. func NewCustomConsumer(consumerKey string, consumerSecret string,
  265. hashFunc crypto.Hash, serviceProvider ServiceProvider,
  266. httpClient *http.Client) *Consumer {
  267. consumer := newConsumer(consumerKey, serviceProvider, httpClient)
  268. consumer.signer = &HMACSigner{
  269. consumerSecret: consumerSecret,
  270. hashFunc: hashFunc,
  271. }
  272. return consumer
  273. }
  274. // Creates a new Consumer instance, with a RSA-SHA1 signer
  275. // - consumerKey:
  276. // value you should obtain from the ServiceProvider when you register your
  277. // application.
  278. //
  279. // - privateKey:
  280. // the private key to use for signatures
  281. //
  282. // - serviceProvider:
  283. // see the documentation for ServiceProvider for how to create this.
  284. //
  285. func NewRSAConsumer(consumerKey string, privateKey *rsa.PrivateKey,
  286. serviceProvider ServiceProvider) *Consumer {
  287. consumer := newConsumer(consumerKey, serviceProvider, nil)
  288. consumer.signer = &RSASigner{
  289. privateKey: privateKey,
  290. hashFunc: crypto.SHA1,
  291. rand: cryptoRand.Reader,
  292. }
  293. return consumer
  294. }
  295. // Creates a new Consumer instance, with a RSA signer
  296. // - consumerKey:
  297. // value you should obtain from the ServiceProvider when you register your
  298. // application.
  299. //
  300. // - privateKey:
  301. // the private key to use for signatures
  302. //
  303. // - hashFunc:
  304. // the crypto.Hash to use for signatures
  305. //
  306. // - serviceProvider:
  307. // see the documentation for ServiceProvider for how to create this.
  308. //
  309. // - httpClient:
  310. // Provides a custom implementation of the httpClient used under the hood
  311. // to make the request. This is especially useful if you want to use
  312. // Google App Engine. Can be nil for default.
  313. //
  314. func NewCustomRSAConsumer(consumerKey string, privateKey *rsa.PrivateKey,
  315. hashFunc crypto.Hash, serviceProvider ServiceProvider,
  316. httpClient *http.Client) *Consumer {
  317. consumer := newConsumer(consumerKey, serviceProvider, httpClient)
  318. consumer.signer = &RSASigner{
  319. privateKey: privateKey,
  320. hashFunc: hashFunc,
  321. rand: cryptoRand.Reader,
  322. }
  323. return consumer
  324. }
  325. // Kicks off the OAuth authorization process.
  326. // - callbackUrl:
  327. // Authorizing a token *requires* redirecting to the service provider. This is the
  328. // URL which the service provider will redirect the user back to after that
  329. // authorization is completed. The service provider will pass back a verification
  330. // code which is necessary to complete the rest of the process (in AuthorizeToken).
  331. // Notes on callbackUrl:
  332. // - Some (all?) service providers allow for setting "oob" (for out-of-band) as a
  333. // callback url. If this is set the service provider will present the
  334. // verification code directly to the user, and you must provide a place for
  335. // them to copy-and-paste it into.
  336. // - Otherwise, the user will be redirected to callbackUrl in the browser, and
  337. // will append a "oauth_verifier=<verifier>" parameter.
  338. //
  339. // This function returns:
  340. // - rtoken:
  341. // A temporary RequestToken, used during the authorization process. You must save
  342. // this since it will be necessary later in the process when calling
  343. // AuthorizeToken().
  344. //
  345. // - url:
  346. // A URL that you should redirect the user to in order that they may authorize you
  347. // to the service provider.
  348. //
  349. // - err:
  350. // Set only if there was an error, nil otherwise.
  351. func (c *Consumer) GetRequestTokenAndUrl(callbackUrl string) (rtoken *RequestToken, loginUrl string, err error) {
  352. return c.GetRequestTokenAndUrlWithParams(callbackUrl, c.AdditionalParams)
  353. }
  354. func (c *Consumer) GetRequestTokenAndUrlWithParams(callbackUrl string, additionalParams map[string]string) (rtoken *RequestToken, loginUrl string, err error) {
  355. params := c.baseParams(c.consumerKey, additionalParams)
  356. if callbackUrl != "" {
  357. params.Add(CALLBACK_PARAM, callbackUrl)
  358. }
  359. req := &request{
  360. method: c.serviceProvider.httpMethod(),
  361. url: c.serviceProvider.RequestTokenUrl,
  362. oauthParams: params,
  363. }
  364. if _, err := c.signRequest(req, ""); err != nil { // We don't have a token secret for the key yet
  365. return nil, "", err
  366. }
  367. resp, err := c.getBody(c.serviceProvider.httpMethod(), c.serviceProvider.RequestTokenUrl, params)
  368. if err != nil {
  369. return nil, "", errors.New("getBody: " + err.Error())
  370. }
  371. requestToken, err := parseRequestToken(*resp)
  372. if err != nil {
  373. return nil, "", errors.New("parseRequestToken: " + err.Error())
  374. }
  375. loginParams := make(url.Values)
  376. for k, v := range c.AdditionalAuthorizationUrlParams {
  377. loginParams.Set(k, v)
  378. }
  379. loginParams.Set(TOKEN_PARAM, requestToken.Token)
  380. loginUrl = c.serviceProvider.AuthorizeTokenUrl + "?" + loginParams.Encode()
  381. return requestToken, loginUrl, nil
  382. }
  383. // After the user has authorized you to the service provider, use this method to turn
  384. // your temporary RequestToken into a permanent AccessToken. You must pass in two values:
  385. // - rtoken:
  386. // The RequestToken returned from GetRequestTokenAndUrl()
  387. //
  388. // - verificationCode:
  389. // The string which passed back from the server, either as the oauth_verifier
  390. // query param appended to callbackUrl *OR* a string manually entered by the user
  391. // if callbackUrl is "oob"
  392. //
  393. // It will return:
  394. // - atoken:
  395. // A permanent AccessToken which can be used to access the user's data (until it is
  396. // revoked by the user or the service provider).
  397. //
  398. // - err:
  399. // Set only if there was an error, nil otherwise.
  400. func (c *Consumer) AuthorizeToken(rtoken *RequestToken, verificationCode string) (atoken *AccessToken, err error) {
  401. return c.AuthorizeTokenWithParams(rtoken, verificationCode, c.AdditionalParams)
  402. }
  403. func (c *Consumer) AuthorizeTokenWithParams(rtoken *RequestToken, verificationCode string, additionalParams map[string]string) (atoken *AccessToken, err error) {
  404. params := map[string]string{
  405. VERIFIER_PARAM: verificationCode,
  406. TOKEN_PARAM: rtoken.Token,
  407. }
  408. return c.makeAccessTokenRequestWithParams(params, rtoken.Secret, additionalParams)
  409. }
  410. // Use the service provider to refresh the AccessToken for a given session.
  411. // Note that this is only supported for service providers that manage an
  412. // authorization session (e.g. Yahoo).
  413. //
  414. // Most providers do not return the SESSION_HANDLE_PARAM needed to refresh
  415. // the token.
  416. //
  417. // See http://oauth.googlecode.com/svn/spec/ext/session/1.0/drafts/1/spec.html
  418. // for more information.
  419. // - accessToken:
  420. // The AccessToken returned from AuthorizeToken()
  421. //
  422. // It will return:
  423. // - atoken:
  424. // An AccessToken which can be used to access the user's data (until it is
  425. // revoked by the user or the service provider).
  426. //
  427. // - err:
  428. // Set if accessToken does not contain the SESSION_HANDLE_PARAM needed to
  429. // refresh the token, or if an error occurred when making the request.
  430. func (c *Consumer) RefreshToken(accessToken *AccessToken) (atoken *AccessToken, err error) {
  431. params := make(map[string]string)
  432. sessionHandle, ok := accessToken.AdditionalData[SESSION_HANDLE_PARAM]
  433. if !ok {
  434. return nil, errors.New("Missing " + SESSION_HANDLE_PARAM + " in access token.")
  435. }
  436. params[SESSION_HANDLE_PARAM] = sessionHandle
  437. params[TOKEN_PARAM] = accessToken.Token
  438. return c.makeAccessTokenRequest(params, accessToken.Secret)
  439. }
  440. // Use the service provider to obtain an AccessToken for a given session
  441. // - params:
  442. // The access token request paramters.
  443. //
  444. // - secret:
  445. // Secret key to use when signing the access token request.
  446. //
  447. // It will return:
  448. // - atoken
  449. // An AccessToken which can be used to access the user's data (until it is
  450. // revoked by the user or the service provider).
  451. //
  452. // - err:
  453. // Set only if there was an error, nil otherwise.
  454. func (c *Consumer) makeAccessTokenRequest(params map[string]string, secret string) (atoken *AccessToken, err error) {
  455. return c.makeAccessTokenRequestWithParams(params, secret, c.AdditionalParams)
  456. }
  457. func (c *Consumer) makeAccessTokenRequestWithParams(params map[string]string, secret string, additionalParams map[string]string) (atoken *AccessToken, err error) {
  458. orderedParams := c.baseParams(c.consumerKey, additionalParams)
  459. for key, value := range params {
  460. orderedParams.Add(key, value)
  461. }
  462. req := &request{
  463. method: c.serviceProvider.httpMethod(),
  464. url: c.serviceProvider.AccessTokenUrl,
  465. oauthParams: orderedParams,
  466. }
  467. if _, err := c.signRequest(req, secret); err != nil {
  468. return nil, err
  469. }
  470. resp, err := c.getBody(c.serviceProvider.httpMethod(), c.serviceProvider.AccessTokenUrl, orderedParams)
  471. if err != nil {
  472. return nil, err
  473. }
  474. return parseAccessToken(*resp)
  475. }
  476. type RoundTripper struct {
  477. consumer *Consumer
  478. token *AccessToken
  479. }
  480. func (c *Consumer) MakeRoundTripper(token *AccessToken) (*RoundTripper, error) {
  481. return &RoundTripper{consumer: c, token: token}, nil
  482. }
  483. func (c *Consumer) MakeHttpClient(token *AccessToken) (*http.Client, error) {
  484. return &http.Client{
  485. Transport: &RoundTripper{consumer: c, token: token},
  486. }, nil
  487. }
  488. // ** DEPRECATED **
  489. // Please call Get on the http client returned by MakeHttpClient instead!
  490. //
  491. // Executes an HTTP Get, authorized via the AccessToken.
  492. // - url:
  493. // The base url, without any query params, which is being accessed
  494. //
  495. // - userParams:
  496. // Any key=value params to be included in the query string
  497. //
  498. // - token:
  499. // The AccessToken returned by AuthorizeToken()
  500. //
  501. // This method returns:
  502. // - resp:
  503. // The HTTP Response resulting from making this request.
  504. //
  505. // - err:
  506. // Set only if there was an error, nil otherwise.
  507. func (c *Consumer) Get(url string, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) {
  508. return c.makeAuthorizedRequest("GET", url, LOC_URL, "", userParams, token)
  509. }
  510. func encodeUserParams(userParams map[string]string) string {
  511. data := url.Values{}
  512. for k, v := range userParams {
  513. data.Add(k, v)
  514. }
  515. return data.Encode()
  516. }
  517. // ** DEPRECATED **
  518. // Please call "Post" on the http client returned by MakeHttpClient instead
  519. func (c *Consumer) PostForm(url string, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) {
  520. return c.PostWithBody(url, "", userParams, token)
  521. }
  522. // ** DEPRECATED **
  523. // Please call "Post" on the http client returned by MakeHttpClient instead
  524. func (c *Consumer) Post(url string, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) {
  525. return c.PostWithBody(url, "", userParams, token)
  526. }
  527. // ** DEPRECATED **
  528. // Please call "Post" on the http client returned by MakeHttpClient instead
  529. func (c *Consumer) PostWithBody(url string, body string, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) {
  530. return c.makeAuthorizedRequest("POST", url, LOC_BODY, body, userParams, token)
  531. }
  532. // ** DEPRECATED **
  533. // Please call "Do" on the http client returned by MakeHttpClient instead
  534. // (and set the "Content-Type" header explicitly in the http.Request)
  535. func (c *Consumer) PostJson(url string, body string, token *AccessToken) (resp *http.Response, err error) {
  536. return c.makeAuthorizedRequest("POST", url, LOC_JSON, body, nil, token)
  537. }
  538. // ** DEPRECATED **
  539. // Please call "Do" on the http client returned by MakeHttpClient instead
  540. // (and set the "Content-Type" header explicitly in the http.Request)
  541. func (c *Consumer) PostXML(url string, body string, token *AccessToken) (resp *http.Response, err error) {
  542. return c.makeAuthorizedRequest("POST", url, LOC_XML, body, nil, token)
  543. }
  544. // ** DEPRECATED **
  545. // Please call "Do" on the http client returned by MakeHttpClient instead
  546. // (and setup the multipart data explicitly in the http.Request)
  547. func (c *Consumer) PostMultipart(url, multipartName string, multipartData io.ReadCloser, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) {
  548. return c.makeAuthorizedRequestReader("POST", url, LOC_MULTIPART, 0, multipartName, multipartData, userParams, token)
  549. }
  550. // ** DEPRECATED **
  551. // Please call "Delete" on the http client returned by MakeHttpClient instead
  552. func (c *Consumer) Delete(url string, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) {
  553. return c.makeAuthorizedRequest("DELETE", url, LOC_URL, "", userParams, token)
  554. }
  555. // ** DEPRECATED **
  556. // Please call "Put" on the http client returned by MakeHttpClient instead
  557. func (c *Consumer) Put(url string, body string, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) {
  558. return c.makeAuthorizedRequest("PUT", url, LOC_URL, body, userParams, token)
  559. }
  560. func (c *Consumer) Debug(enabled bool) {
  561. c.debug = enabled
  562. c.signer.Debug(enabled)
  563. }
  564. type pair struct {
  565. key string
  566. value string
  567. }
  568. type pairs []pair
  569. func (p pairs) Len() int { return len(p) }
  570. func (p pairs) Less(i, j int) bool { return p[i].key < p[j].key }
  571. func (p pairs) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  572. // This function has basically turned into a backwards compatibility layer
  573. // between the old API (where clients explicitly called consumer.Get()
  574. // consumer.Post() etc), and the new API (which takes actual http.Requests)
  575. //
  576. // So, here we construct the appropriate HTTP request for the inputs.
  577. func (c *Consumer) makeAuthorizedRequestReader(method string, urlString string, dataLocation DataLocation, contentLength int, multipartName string, body io.ReadCloser, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) {
  578. urlObject, err := url.Parse(urlString)
  579. if err != nil {
  580. return nil, err
  581. }
  582. request := &http.Request{
  583. Method: method,
  584. URL: urlObject,
  585. Header: http.Header{},
  586. Body: body,
  587. ContentLength: int64(contentLength),
  588. }
  589. vals := url.Values{}
  590. for k, v := range userParams {
  591. vals.Add(k, v)
  592. }
  593. if dataLocation != LOC_BODY {
  594. request.URL.RawQuery = vals.Encode()
  595. request.URL.RawQuery = strings.Replace(
  596. request.URL.RawQuery, ";", "%3B", -1)
  597. } else {
  598. // TODO(mrjones): validate that we're not overrideing an exising body?
  599. request.Body = ioutil.NopCloser(strings.NewReader(vals.Encode()))
  600. request.ContentLength = int64(len(vals.Encode()))
  601. }
  602. for k, vs := range c.AdditionalHeaders {
  603. for _, v := range vs {
  604. request.Header.Set(k, v)
  605. }
  606. }
  607. if dataLocation == LOC_BODY {
  608. request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  609. }
  610. if dataLocation == LOC_JSON {
  611. request.Header.Set("Content-Type", "application/json")
  612. }
  613. if dataLocation == LOC_XML {
  614. request.Header.Set("Content-Type", "application/xml")
  615. }
  616. if dataLocation == LOC_MULTIPART {
  617. pipeReader, pipeWriter := io.Pipe()
  618. writer := multipart.NewWriter(pipeWriter)
  619. if request.URL.Host == "www.mrjon.es" &&
  620. request.URL.Path == "/unittest" {
  621. writer.SetBoundary("UNITTESTBOUNDARY")
  622. }
  623. go func(body io.Reader) {
  624. part, err := writer.CreateFormFile(multipartName, "/no/matter")
  625. if err != nil {
  626. writer.Close()
  627. pipeWriter.CloseWithError(err)
  628. return
  629. }
  630. _, err = io.Copy(part, body)
  631. if err != nil {
  632. writer.Close()
  633. pipeWriter.CloseWithError(err)
  634. return
  635. }
  636. writer.Close()
  637. pipeWriter.Close()
  638. }(body)
  639. request.Body = pipeReader
  640. request.Header.Set("Content-Type", writer.FormDataContentType())
  641. }
  642. rt := RoundTripper{consumer: c, token: token}
  643. resp, err = rt.RoundTrip(request)
  644. if err != nil {
  645. return resp, err
  646. }
  647. if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
  648. defer resp.Body.Close()
  649. bytes, _ := ioutil.ReadAll(resp.Body)
  650. return resp, HTTPExecuteError{
  651. RequestHeaders: "",
  652. ResponseBodyBytes: bytes,
  653. Status: resp.Status,
  654. StatusCode: resp.StatusCode,
  655. }
  656. }
  657. return resp, nil
  658. }
  659. // cloneReq clones the src http.Request, making deep copies of the Header and
  660. // the URL but shallow copies of everything else
  661. func cloneReq(src *http.Request) *http.Request {
  662. dst := &http.Request{}
  663. *dst = *src
  664. dst.Header = make(http.Header, len(src.Header))
  665. for k, s := range src.Header {
  666. dst.Header[k] = append([]string(nil), s...)
  667. }
  668. if src.URL != nil {
  669. dst.URL = cloneURL(src.URL)
  670. }
  671. return dst
  672. }
  673. // cloneURL shallow clones the src *url.URL
  674. func cloneURL(src *url.URL) *url.URL {
  675. dst := &url.URL{}
  676. *dst = *src
  677. return dst
  678. }
  679. func canonicalizeUrl(u *url.URL) string {
  680. var buf bytes.Buffer
  681. buf.WriteString(u.Scheme)
  682. buf.WriteString("://")
  683. buf.WriteString(u.Host)
  684. buf.WriteString(u.Path)
  685. return buf.String()
  686. }
  687. func parseBody(request *http.Request) (map[string]string, error) {
  688. userParams := map[string]string{}
  689. // TODO(mrjones): factor parameter extraction into a separate method
  690. if request.Header.Get("Content-Type") !=
  691. "application/x-www-form-urlencoded" {
  692. // Most of the time we get parameters from the query string:
  693. for k, vs := range request.URL.Query() {
  694. if len(vs) != 1 {
  695. return nil, fmt.Errorf("Must have exactly one value per param")
  696. }
  697. userParams[k] = vs[0]
  698. }
  699. } else {
  700. // x-www-form-urlencoded parameters come from the body instead:
  701. defer request.Body.Close()
  702. originalBody, err := ioutil.ReadAll(request.Body)
  703. if err != nil {
  704. return nil, err
  705. }
  706. // If there was a body, we have to re-install it
  707. // (because we've ruined it by reading it).
  708. request.Body = ioutil.NopCloser(bytes.NewReader(originalBody))
  709. params, err := url.ParseQuery(string(originalBody))
  710. if err != nil {
  711. return nil, err
  712. }
  713. for k, vs := range params {
  714. if len(vs) != 1 {
  715. return nil, fmt.Errorf("Must have exactly one value per param")
  716. }
  717. userParams[k] = vs[0]
  718. }
  719. }
  720. return userParams, nil
  721. }
  722. func paramsToSortedPairs(params map[string]string) pairs {
  723. // Sort parameters alphabetically
  724. paramPairs := make(pairs, len(params))
  725. i := 0
  726. for key, value := range params {
  727. paramPairs[i] = pair{key: key, value: value}
  728. i++
  729. }
  730. sort.Sort(paramPairs)
  731. return paramPairs
  732. }
  733. func calculateBodyHash(request *http.Request, s signer) (string, error) {
  734. if request.Header.Get("Content-Type") ==
  735. "application/x-www-form-urlencoded" {
  736. return "", nil
  737. }
  738. var originalBody []byte
  739. if request.Body != nil {
  740. var err error
  741. defer request.Body.Close()
  742. originalBody, err = ioutil.ReadAll(request.Body)
  743. if err != nil {
  744. return "", err
  745. }
  746. // If there was a body, we have to re-install it
  747. // (because we've ruined it by reading it).
  748. request.Body = ioutil.NopCloser(bytes.NewReader(originalBody))
  749. }
  750. h := s.HashFunc().New()
  751. h.Write(originalBody)
  752. rawSignature := h.Sum(nil)
  753. return base64.StdEncoding.EncodeToString(rawSignature), nil
  754. }
  755. func (rt *RoundTripper) RoundTrip(userRequest *http.Request) (*http.Response, error) {
  756. serverRequest := cloneReq(userRequest)
  757. allParams := rt.consumer.baseParams(
  758. rt.consumer.consumerKey, rt.consumer.AdditionalParams)
  759. // Do not add the "oauth_token" parameter, if the access token has not been
  760. // specified. By omitting this parameter when it is not specified, allows
  761. // two-legged OAuth calls.
  762. if len(rt.token.Token) > 0 {
  763. allParams.Add(TOKEN_PARAM, rt.token.Token)
  764. }
  765. if rt.consumer.serviceProvider.BodyHash {
  766. bodyHash, err := calculateBodyHash(serverRequest, rt.consumer.signer)
  767. if err != nil {
  768. return nil, err
  769. }
  770. if bodyHash != "" {
  771. allParams.Add(BODY_HASH_PARAM, bodyHash)
  772. }
  773. }
  774. authParams := allParams.Clone()
  775. // TODO(mrjones): put these directly into the paramPairs below?
  776. userParams, err := parseBody(serverRequest)
  777. if err != nil {
  778. return nil, err
  779. }
  780. paramPairs := paramsToSortedPairs(userParams)
  781. for i := range paramPairs {
  782. allParams.Add(paramPairs[i].key, paramPairs[i].value)
  783. }
  784. signingURL := cloneURL(serverRequest.URL)
  785. if host := serverRequest.Host; host != "" {
  786. signingURL.Host = host
  787. }
  788. baseString := rt.consumer.requestString(serverRequest.Method, canonicalizeUrl(signingURL), allParams)
  789. signature, err := rt.consumer.signer.Sign(baseString, rt.token.Secret)
  790. if err != nil {
  791. return nil, err
  792. }
  793. authParams.Add(SIGNATURE_PARAM, signature)
  794. // Set auth header.
  795. oauthHdr := OAUTH_HEADER
  796. for pos, key := range authParams.Keys() {
  797. for innerPos, value := range authParams.Get(key) {
  798. if pos+innerPos > 0 {
  799. oauthHdr += ","
  800. }
  801. oauthHdr += key + "=\"" + value + "\""
  802. }
  803. }
  804. serverRequest.Header.Add(HTTP_AUTH_HEADER, oauthHdr)
  805. if rt.consumer.debug {
  806. fmt.Printf("Request: %v\n", serverRequest)
  807. }
  808. resp, err := rt.consumer.HttpClient.Do(serverRequest)
  809. if err != nil {
  810. return resp, err
  811. }
  812. return resp, nil
  813. }
  814. func (c *Consumer) makeAuthorizedRequest(method string, url string, dataLocation DataLocation, body string, userParams map[string]string, token *AccessToken) (resp *http.Response, err error) {
  815. return c.makeAuthorizedRequestReader(method, url, dataLocation, len(body), "", ioutil.NopCloser(strings.NewReader(body)), userParams, token)
  816. }
  817. type request struct {
  818. method string
  819. url string
  820. oauthParams *OrderedParams
  821. userParams map[string]string
  822. }
  823. type HttpClient interface {
  824. Do(req *http.Request) (resp *http.Response, err error)
  825. }
  826. type clock interface {
  827. Seconds() int64
  828. Nanos() int64
  829. }
  830. type nonceGenerator interface {
  831. Int63() int64
  832. }
  833. type key interface {
  834. String() string
  835. }
  836. type signer interface {
  837. Sign(message string, tokenSecret string) (string, error)
  838. Verify(message string, signature string) error
  839. SignatureMethod() string
  840. HashFunc() crypto.Hash
  841. Debug(enabled bool)
  842. }
  843. type defaultClock struct{}
  844. func (*defaultClock) Seconds() int64 {
  845. return time.Now().Unix()
  846. }
  847. func (*defaultClock) Nanos() int64 {
  848. return time.Now().UnixNano()
  849. }
  850. func (c *Consumer) signRequest(req *request, tokenSecret string) (*request, error) {
  851. baseString := c.requestString(req.method, req.url, req.oauthParams)
  852. signature, err := c.signer.Sign(baseString, tokenSecret)
  853. if err != nil {
  854. return nil, err
  855. }
  856. req.oauthParams.Add(SIGNATURE_PARAM, signature)
  857. return req, nil
  858. }
  859. // Obtains an AccessToken from the response of a service provider.
  860. // - data:
  861. // The response body.
  862. //
  863. // This method returns:
  864. // - atoken:
  865. // The AccessToken generated from the response body.
  866. //
  867. // - err:
  868. // Set if an AccessToken could not be parsed from the given input.
  869. func parseAccessToken(data string) (atoken *AccessToken, err error) {
  870. parts, err := url.ParseQuery(data)
  871. if err != nil {
  872. return nil, err
  873. }
  874. tokenParam := parts[TOKEN_PARAM]
  875. parts.Del(TOKEN_PARAM)
  876. if len(tokenParam) < 1 {
  877. return nil, errors.New("Missing " + TOKEN_PARAM + " in response. " +
  878. "Full response body: '" + data + "'")
  879. }
  880. tokenSecretParam := parts[TOKEN_SECRET_PARAM]
  881. parts.Del(TOKEN_SECRET_PARAM)
  882. if len(tokenSecretParam) < 1 {
  883. return nil, errors.New("Missing " + TOKEN_SECRET_PARAM + " in response." +
  884. "Full response body: '" + data + "'")
  885. }
  886. additionalData := parseAdditionalData(parts)
  887. return &AccessToken{tokenParam[0], tokenSecretParam[0], additionalData}, nil
  888. }
  889. func parseRequestToken(data string) (*RequestToken, error) {
  890. parts, err := url.ParseQuery(data)
  891. if err != nil {
  892. return nil, err
  893. }
  894. tokenParam := parts[TOKEN_PARAM]
  895. if len(tokenParam) < 1 {
  896. return nil, errors.New("Missing " + TOKEN_PARAM + " in response. " +
  897. "Full response body: '" + data + "'")
  898. }
  899. tokenSecretParam := parts[TOKEN_SECRET_PARAM]
  900. if len(tokenSecretParam) < 1 {
  901. return nil, errors.New("Missing " + TOKEN_SECRET_PARAM + " in response." +
  902. "Full response body: '" + data + "'")
  903. }
  904. return &RequestToken{tokenParam[0], tokenSecretParam[0]}, nil
  905. }
  906. func (c *Consumer) baseParams(consumerKey string, additionalParams map[string]string) *OrderedParams {
  907. params := NewOrderedParams()
  908. params.Add(VERSION_PARAM, OAUTH_VERSION)
  909. params.Add(SIGNATURE_METHOD_PARAM, c.signer.SignatureMethod())
  910. params.Add(TIMESTAMP_PARAM, strconv.FormatInt(c.clock.Seconds(), 10))
  911. params.Add(NONCE_PARAM, strconv.FormatInt(c.nonceGenerator.Int63(), 10))
  912. params.Add(CONSUMER_KEY_PARAM, consumerKey)
  913. for key, value := range additionalParams {
  914. params.Add(key, value)
  915. }
  916. return params
  917. }
  918. func parseAdditionalData(parts url.Values) map[string]string {
  919. params := make(map[string]string)
  920. for key, value := range parts {
  921. if len(value) > 0 {
  922. params[key] = value[0]
  923. }
  924. }
  925. return params
  926. }
  927. type HMACSigner struct {
  928. consumerSecret string
  929. hashFunc crypto.Hash
  930. debug bool
  931. }
  932. func (s *HMACSigner) Debug(enabled bool) {
  933. s.debug = enabled
  934. }
  935. func (s *HMACSigner) Sign(message string, tokenSecret string) (string, error) {
  936. key := escape(s.consumerSecret) + "&" + escape(tokenSecret)
  937. if s.debug {
  938. fmt.Println("Signing:", message)
  939. fmt.Println("Key:", key)
  940. }
  941. h := hmac.New(s.HashFunc().New, []byte(key))
  942. h.Write([]byte(message))
  943. rawSignature := h.Sum(nil)
  944. base64signature := base64.StdEncoding.EncodeToString(rawSignature)
  945. if s.debug {
  946. fmt.Println("Base64 signature:", base64signature)
  947. }
  948. return base64signature, nil
  949. }
  950. func (s *HMACSigner) Verify(message string, signature string) error {
  951. if s.debug {
  952. fmt.Println("Verifying Base64 signature:", signature)
  953. }
  954. validSignature, err := s.Sign(message, "")
  955. if err != nil {
  956. return err
  957. }
  958. if validSignature != signature {
  959. decodedSigniture, _ := url.QueryUnescape(signature)
  960. if validSignature != decodedSigniture {
  961. return fmt.Errorf("signature did not match")
  962. }
  963. }
  964. return nil
  965. }
  966. func (s *HMACSigner) SignatureMethod() string {
  967. return SIGNATURE_METHOD_HMAC + HASH_METHOD_MAP[s.HashFunc()]
  968. }
  969. func (s *HMACSigner) HashFunc() crypto.Hash {
  970. return s.hashFunc
  971. }
  972. type RSASigner struct {
  973. debug bool
  974. rand io.Reader
  975. privateKey *rsa.PrivateKey
  976. hashFunc crypto.Hash
  977. }
  978. func (s *RSASigner) Debug(enabled bool) {
  979. s.debug = enabled
  980. }
  981. func (s *RSASigner) Sign(message string, tokenSecret string) (string, error) {
  982. if s.debug {
  983. fmt.Println("Signing:", message)
  984. }
  985. h := s.HashFunc().New()
  986. h.Write([]byte(message))
  987. digest := h.Sum(nil)
  988. signature, err := rsa.SignPKCS1v15(s.rand, s.privateKey, s.HashFunc(), digest)
  989. if err != nil {
  990. return "", nil
  991. }
  992. base64signature := base64.StdEncoding.EncodeToString(signature)
  993. if s.debug {
  994. fmt.Println("Base64 signature:", base64signature)
  995. }
  996. return base64signature, nil
  997. }
  998. func (s *RSASigner) Verify(message string, base64signature string) error {
  999. if s.debug {
  1000. fmt.Println("Verifying:", message)
  1001. fmt.Println("Verifying Base64 signature:", base64signature)
  1002. }
  1003. h := s.HashFunc().New()
  1004. h.Write([]byte(message))
  1005. digest := h.Sum(nil)
  1006. signature, err := base64.StdEncoding.DecodeString(base64signature)
  1007. if err != nil {
  1008. return err
  1009. }
  1010. return rsa.VerifyPKCS1v15(&s.privateKey.PublicKey, s.HashFunc(), digest, signature)
  1011. }
  1012. func (s *RSASigner) SignatureMethod() string {
  1013. return SIGNATURE_METHOD_RSA + HASH_METHOD_MAP[s.HashFunc()]
  1014. }
  1015. func (s *RSASigner) HashFunc() crypto.Hash {
  1016. return s.hashFunc
  1017. }
  1018. func escape(s string) string {
  1019. t := make([]byte, 0, 3*len(s))
  1020. for i := 0; i < len(s); i++ {
  1021. c := s[i]
  1022. if isEscapable(c) {
  1023. t = append(t, '%')
  1024. t = append(t, "0123456789ABCDEF"[c>>4])
  1025. t = append(t, "0123456789ABCDEF"[c&15])
  1026. } else {
  1027. t = append(t, s[i])
  1028. }
  1029. }
  1030. return string(t)
  1031. }
  1032. func isEscapable(b byte) bool {
  1033. return !('A' <= b && b <= 'Z' || 'a' <= b && b <= 'z' || '0' <= b && b <= '9' || b == '-' || b == '.' || b == '_' || b == '~')
  1034. }
  1035. func (c *Consumer) requestString(method string, url string, params *OrderedParams) string {
  1036. result := method + "&" + escape(url)
  1037. for pos, key := range params.Keys() {
  1038. for innerPos, value := range params.Get(key) {
  1039. if pos+innerPos == 0 {
  1040. result += "&"
  1041. } else {
  1042. result += escape("&")
  1043. }
  1044. result += escape(fmt.Sprintf("%s=%s", key, value))
  1045. }
  1046. }
  1047. return result
  1048. }
  1049. func (c *Consumer) getBody(method, url string, oauthParams *OrderedParams) (*string, error) {
  1050. resp, err := c.httpExecute(method, url, "", 0, nil, oauthParams)
  1051. if err != nil {
  1052. return nil, errors.New("httpExecute: " + err.Error())
  1053. }
  1054. bodyBytes, err := ioutil.ReadAll(resp.Body)
  1055. resp.Body.Close()
  1056. if err != nil {
  1057. return nil, errors.New("ReadAll: " + err.Error())
  1058. }
  1059. bodyStr := string(bodyBytes)
  1060. if c.debug {
  1061. fmt.Printf("STATUS: %d %s\n", resp.StatusCode, resp.Status)
  1062. fmt.Println("BODY RESPONSE: " + bodyStr)
  1063. }
  1064. return &bodyStr, nil
  1065. }
  1066. // HTTPExecuteError signals that a call to httpExecute failed.
  1067. type HTTPExecuteError struct {
  1068. // RequestHeaders provides a stringified listing of request headers.
  1069. RequestHeaders string
  1070. // ResponseBodyBytes is the response read into a byte slice.
  1071. ResponseBodyBytes []byte
  1072. // Status is the status code string response.
  1073. Status string
  1074. // StatusCode is the parsed status code.
  1075. StatusCode int
  1076. }
  1077. // Error provides a printable string description of an HTTPExecuteError.
  1078. func (e HTTPExecuteError) Error() string {
  1079. return "HTTP response is not 200/OK as expected. Actual response: \n" +
  1080. "\tResponse Status: '" + e.Status + "'\n" +
  1081. "\tResponse Code: " + strconv.Itoa(e.StatusCode) + "\n" +
  1082. "\tResponse Body: " + string(e.ResponseBodyBytes) + "\n" +
  1083. "\tRequest Headers: " + e.RequestHeaders
  1084. }
  1085. func (c *Consumer) httpExecute(
  1086. method string, urlStr string, contentType string, contentLength int, body io.Reader, oauthParams *OrderedParams) (*http.Response, error) {
  1087. // Create base request.
  1088. req, err := http.NewRequest(method, urlStr, body)
  1089. if err != nil {
  1090. return nil, errors.New("NewRequest failed: " + err.Error())
  1091. }
  1092. // Set auth header.
  1093. req.Header = http.Header{}
  1094. oauthHdr := "OAuth "
  1095. for pos, key := range oauthParams.Keys() {
  1096. for innerPos, value := range oauthParams.Get(key) {
  1097. if pos+innerPos > 0 {
  1098. oauthHdr += ","
  1099. }
  1100. oauthHdr += key + "=\"" + value + "\""
  1101. }
  1102. }
  1103. req.Header.Add("Authorization", oauthHdr)
  1104. // Add additional custom headers
  1105. for key, vals := range c.AdditionalHeaders {
  1106. for _, val := range vals {
  1107. req.Header.Add(key, val)
  1108. }
  1109. }
  1110. // Set contentType if passed.
  1111. if contentType != "" {
  1112. req.Header.Set("Content-Type", contentType)
  1113. }
  1114. // Set contentLength if passed.
  1115. if contentLength > 0 {
  1116. req.Header.Set("Content-Length", strconv.Itoa(contentLength))
  1117. }
  1118. if c.debug {
  1119. fmt.Printf("Request: %v\n", req)
  1120. }
  1121. resp, err := c.HttpClient.Do(req)
  1122. if err != nil {
  1123. return nil, errors.New("Do: " + err.Error())
  1124. }
  1125. debugHeader := ""
  1126. for k, vals := range req.Header {
  1127. for _, val := range vals {
  1128. debugHeader += "[key: " + k + ", val: " + val + "]"
  1129. }
  1130. }
  1131. // StatusMultipleChoices is 300, any 2xx response should be treated as success
  1132. if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
  1133. defer resp.Body.Close()
  1134. bytes, _ := ioutil.ReadAll(resp.Body)
  1135. return resp, HTTPExecuteError{
  1136. RequestHeaders: debugHeader,
  1137. ResponseBodyBytes: bytes,
  1138. Status: resp.Status,
  1139. StatusCode: resp.StatusCode,
  1140. }
  1141. }
  1142. return resp, err
  1143. }
  1144. //
  1145. // String Sorting helpers
  1146. //
  1147. type ByValue []string
  1148. func (a ByValue) Len() int {
  1149. return len(a)
  1150. }
  1151. func (a ByValue) Swap(i, j int) {
  1152. a[i], a[j] = a[j], a[i]
  1153. }
  1154. func (a ByValue) Less(i, j int) bool {
  1155. return a[i] < a[j]
  1156. }
  1157. //
  1158. // ORDERED PARAMS
  1159. //
  1160. type OrderedParams struct {
  1161. allParams map[string][]string
  1162. keyOrdering []string
  1163. }
  1164. func NewOrderedParams() *OrderedParams {
  1165. return &OrderedParams{
  1166. allParams: make(map[string][]string),
  1167. keyOrdering: make([]string, 0),
  1168. }
  1169. }
  1170. func (o *OrderedParams) Get(key string) []string {
  1171. sort.Sort(ByValue(o.allParams[key]))
  1172. return o.allParams[key]
  1173. }
  1174. func (o *OrderedParams) Keys() []string {
  1175. sort.Sort(o)
  1176. return o.keyOrdering
  1177. }
  1178. func (o *OrderedParams) Add(key, value string) {
  1179. o.AddUnescaped(key, escape(value))
  1180. }
  1181. func (o *OrderedParams) AddUnescaped(key, value string) {
  1182. if _, exists := o.allParams[key]; !exists {
  1183. o.keyOrdering = append(o.keyOrdering, key)
  1184. o.allParams[key] = make([]string, 1)
  1185. o.allParams[key][0] = value
  1186. } else {
  1187. o.allParams[key] = append(o.allParams[key], value)
  1188. }
  1189. }
  1190. func (o *OrderedParams) Len() int {
  1191. return len(o.keyOrdering)
  1192. }
  1193. func (o *OrderedParams) Less(i int, j int) bool {
  1194. return o.keyOrdering[i] < o.keyOrdering[j]
  1195. }
  1196. func (o *OrderedParams) Swap(i int, j int) {
  1197. o.keyOrdering[i], o.keyOrdering[j] = o.keyOrdering[j], o.keyOrdering[i]
  1198. }
  1199. func (o *OrderedParams) Clone() *OrderedParams {
  1200. clone := NewOrderedParams()
  1201. for _, key := range o.Keys() {
  1202. for _, value := range o.Get(key) {
  1203. clone.AddUnescaped(key, value)
  1204. }
  1205. }
  1206. return clone
  1207. }