Created
June 23, 2011 17:16
-
-
Save dtjm/1043031 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 mypackage | |
| import ( | |
| "encoding/base64" | |
| "crypto/hmac" | |
| "http" | |
| "testing" | |
| "time" | |
| ) | |
| func TestHMAC(t *testing.T) { | |
| r, err := http.NewRequest("GET", "http://server/api/model", | |
| nil) | |
| if err != nil { | |
| t.Fatal("Couldn't create http.Request: ", err) | |
| } | |
| // Set Date header | |
| date := time.UTC().String() | |
| r.Header.Set("Date", date) | |
| // Set header for Request signature | |
| sig := requestSignature(r, "secret key") | |
| r.Header.Set("X-Request-Signature", sig) | |
| t.Log("sig: ", r.Header.Get("X-Request-Signature")) | |
| c := http.Client{} | |
| resp, err := c.Do(r) | |
| if err != nil { | |
| t.Fatal("Couldn't perform request: ", err) | |
| } else if resp.StatusCode != 200 { | |
| t.Fatal("Should get status 200.\n", resp.Status) | |
| } | |
| } | |
| func requestSignature(req *http.Request, secret string) string { | |
| hash := hmac.NewSHA1([]byte(secret)) | |
| hash.Write([]byte(req.Method)) | |
| hash.Write([]byte(req.URL.RawPath)) | |
| hash.Write([]byte(req.Header.Get("Date"))) | |
| sum := hash.Sum() | |
| return string(base64Encode(sum)) | |
| } | |
| func base64Encode(in []byte) []byte { | |
| dst := make([]byte, base64.StdEncoding.EncodedLen(len(in))) | |
| base64.StdEncoding.Encode(dst, in) | |
| return dst | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment