signCookies.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // +build example
  2. package main
  3. import (
  4. "flag"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "time"
  9. "github.com/aws/aws-sdk-go/service/cloudfront/sign"
  10. )
  11. // Makes a request for object using CloudFront cookie signing, and outputs
  12. // the contents of the object to stdout.
  13. //
  14. // Usage example:
  15. // signCookies -file <privkey file> -id <keyId> -r <resource pattern> -g <object to get>
  16. func main() {
  17. var keyFile string // Private key PEM file
  18. var keyID string // Key pair ID of CloudFront key pair
  19. var resource string // CloudFront resource pattern
  20. var object string // S3 object frontented by CloudFront
  21. flag.StringVar(&keyFile, "file", "", "private key file")
  22. flag.StringVar(&keyID, "id", "", "key pair id")
  23. flag.StringVar(&resource, "r", "", "resource to request")
  24. flag.StringVar(&object, "g", "", "object to get")
  25. flag.Parse()
  26. // Load the PEM file into memory so it can be used by the signer
  27. privKey, err := sign.LoadPEMPrivKeyFile(keyFile)
  28. if err != nil {
  29. fmt.Println("failed to load key,", err)
  30. return
  31. }
  32. // Create the new CookieSigner to get signed cookies for CloudFront
  33. // resource requests
  34. signer := sign.NewCookieSigner(keyID, privKey)
  35. // Get the cookies for the resource. These will be used
  36. // to make the requests with
  37. cookies, err := signer.Sign(resource, time.Now().Add(1*time.Hour))
  38. if err != nil {
  39. fmt.Println("failed to sign cookies", err)
  40. return
  41. }
  42. // Use the cookies in a http.Client to show how they allow the client
  43. // to request resources from CloudFront.
  44. req, err := http.NewRequest("GET", object, nil)
  45. fmt.Println("Cookies:")
  46. for _, c := range cookies {
  47. fmt.Printf("%s=%s;\n", c.Name, c.Value)
  48. req.AddCookie(c)
  49. }
  50. // Send and handle the response. For a successful response the object's
  51. // content will be written to stdout. The same process could be applied
  52. // to a http service written cookies to the response but using
  53. // http.SetCookie(w, c,) on the ResponseWriter.
  54. resp, err := http.DefaultClient.Do(req)
  55. if err != nil {
  56. fmt.Println("failed to send request", err)
  57. return
  58. }
  59. defer resp.Body.Close()
  60. b, err := ioutil.ReadAll(resp.Body)
  61. if err != nil {
  62. fmt.Println("failed to read requested body", err)
  63. return
  64. }
  65. fmt.Println("Response:", resp.Status)
  66. fmt.Println(string(b))
  67. }