Last active
November 21, 2016 17:51
-
-
Save ThomasAlxDmy/d60372970884ae797fdaed227a2dafee to your computer and use it in GitHub Desktop.
aws s3 S3AuthorizedUpload
This file contains 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
// Server | |
func S3signatureGeneration() string{ | |
now := time.Now().UTC() | |
policyDate, dateStamp := now.Format(ISO8601BasicFormat), now.Format(ISO8601BasicFormatShort) | |
expirationTime := now.Add(uploadValidity + 5*time.Minute).Format(ISO8601) | |
allowedPath := "test/" | |
credential := XAMZCredential(awsAccessKeyID, dateStamp, awsRegion) | |
str := "{ \"expiration\": \"%s\",\"conditions\": [{\"bucket\": \"%s\"},[\"starts-with\", \"$key\", \"%s\"],{\"acl\": \"%s\"},{\"x-amz-credential\": \"%s\"},{\"x-amz-algorithm\": \"AWS4-HMAC-SHA256\"},{\"x-amz-date\": \"%s\" }]}" | |
finalStr := fmt.Sprintf(str, expirationTime, awsBucket, allowedPath, acl, credential, policyDate) | |
base64Policy := base64.StdEncoding.EncodeToString([]byte(finalStr)) | |
SigningKey := getSignatureKey(awsSecretAccessKey, dateStamp, awsRegion, "s3") | |
S3Signature := hex.EncodeToString(hmacSHA256(SigningKey, []byte(base64Policy))) | |
return S3Signature | |
} | |
//client | |
func Upload(s3Filename string, config *Config){ | |
fields := [][]string{ | |
[]string{"key", config.Path + s3Filename}, | |
[]string{"acl", config.ACL}, | |
[]string{"X-Amz-Credential", config.Credential}, | |
[]string{"X-Amz-Algorithm", "AWS4-HMAC-SHA256"}, | |
[]string{"X-Amz-Date", config.PolicyDate}, | |
[]string{"Policy", config.Base64Policy}, | |
[]string{"X-Amz-Signature", config.S3Signature}, | |
[]string{"file", "{\"test\": \"a\"}"}, | |
} | |
S3AuthorizedUpload(fmt.Sprintf("http://%s.s3.amazonaws.com", config.AwsBucket), fields) | |
} | |
func S3AuthorizedUpload(url string, fields [][]string) error { | |
var b bytes.Buffer | |
w := multipart.NewWriter(&b) | |
for _, value := range fields { | |
fw, err := w.CreateFormField(value[0]) | |
if err != nil { | |
return err | |
} | |
if _, err := fw.Write([]byte(value[1])); err != nil { | |
return err | |
} | |
} | |
w.Close() | |
req, err := http.NewRequest("POST", url, &b) | |
if err != nil { | |
return err | |
} | |
req.Header.Set("Content-Type", w.FormDataContentType()) | |
client := &http.Client{} | |
res, err := client.Do(req) | |
if err != nil { | |
return err | |
} | |
if res.StatusCode != http.StatusOK { | |
err = fmt.Errorf("bad status: %s", res.Status) | |
} | |
if response, err := ioutil.ReadAll(res.Body); err != nil { | |
return err | |
} else { | |
log.Println(string(response)) | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment