signCookies.go 2.2 KB

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