Created
July 9, 2012 21:46
-
-
Save bsdf/3079210 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"crypto/hmac" | |
"crypto/sha1" | |
"encoding/base64" | |
"fmt" | |
"net/url" | |
"sort" | |
) | |
const ( | |
consumerSecret = "kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw" | |
oauthTokenSecret = "LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE" | |
) | |
type RestMethod struct { | |
Url string | |
Method string | |
Params map[string]string | |
} | |
func main() { | |
params := make(map[string]string) | |
params["oauth_consumer_key"] = "xvz1evFS4wEEPTGEFPHBog" | |
params["oauth_version"] = "1.0" | |
params["include_entities"] = "true" | |
params["oauth_nonce"] = "kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg" | |
params["oauth_token"] = "370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb" | |
params["oauth_signature_method"] = "HMAC-SHA1" | |
params["oauth_timestamp"] = "1318622958" | |
method := RestMethod{ | |
Url: "https://api.twitter.com/1/statuses/update.json", | |
Method: "POST", | |
Params: params, | |
} | |
str := generateSignatureBase(method) | |
fmt.Println(str) | |
sig := generateOAuthSignature(str) | |
fmt.Println(sig) | |
} | |
func generateOAuthSignature(signatureBase string) string { | |
signingKey := fmt.Sprintf("%s&%s", consumerSecret, oauthTokenSecret) | |
h := hmac.New(sha1.New, []byte(signingKey)) | |
h.Write([]byte(signatureBase)) | |
return base64.StdEncoding.EncodeToString(h.Sum(nil)) | |
} | |
func generateSignatureBase(m RestMethod) string { | |
var buffer bytes.Buffer | |
// write method and url to buffer | |
buffer.WriteString(m.Method + "&") | |
buffer.WriteString(encode(m.Url) + "&") | |
// sort map keys | |
sortedKeys := sortMapKeys(m.Params) | |
// write each parameter to buffer | |
for _, v := range sortedKeys { | |
buffer.WriteString(encode(fmt.Sprintf("%s=%s&", v, m.Params[v]))) | |
} | |
// turn buffer into string | |
output := buffer.String() | |
// remove trailing & | |
return output[:len(output)-1] | |
} | |
func sortMapKeys(m map[string]string) []string { | |
keys := make([]string, len(m)) | |
i := 0 | |
for k, _ := range m { | |
keys[i] = k | |
i++ | |
} | |
sort.Strings(keys) | |
return keys | |
} | |
// wrapper for url.QueryEscape | |
func encode(str string) string { | |
return url.QueryEscape(str) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment