1
0

request.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package alils
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "fmt"
  6. "net/http"
  7. )
  8. // request sends a request to SLS.
  9. func request(project *LogProject, method, uri string, headers map[string]string,
  10. body []byte) (resp *http.Response, err error) {
  11. // The caller should provide 'x-sls-bodyrawsize' header
  12. if _, ok := headers["x-sls-bodyrawsize"]; !ok {
  13. err = fmt.Errorf("Can't find 'x-sls-bodyrawsize' header")
  14. return
  15. }
  16. // SLS public request headers
  17. headers["Host"] = project.Name + "." + project.Endpoint
  18. headers["Date"] = nowRFC1123()
  19. headers["x-sls-apiversion"] = version
  20. headers["x-sls-signaturemethod"] = signatureMethod
  21. if body != nil {
  22. bodyMD5 := fmt.Sprintf("%X", md5.Sum(body))
  23. headers["Content-MD5"] = bodyMD5
  24. if _, ok := headers["Content-Type"]; !ok {
  25. err = fmt.Errorf("Can't find 'Content-Type' header")
  26. return
  27. }
  28. }
  29. // Calc Authorization
  30. // Authorization = "SLS <AccessKeyId>:<Signature>"
  31. digest, err := signature(project, method, uri, headers)
  32. if err != nil {
  33. return
  34. }
  35. auth := fmt.Sprintf("SLS %v:%v", project.AccessKeyId, digest)
  36. headers["Authorization"] = auth
  37. // Initialize http request
  38. reader := bytes.NewReader(body)
  39. urlStr := fmt.Sprintf("http://%v.%v%v", project.Name, project.Endpoint, uri)
  40. req, err := http.NewRequest(method, urlStr, reader)
  41. if err != nil {
  42. return
  43. }
  44. for k, v := range headers {
  45. req.Header.Add(k, v)
  46. }
  47. // Get ready to do request
  48. resp, err = http.DefaultClient.Do(req)
  49. if err != nil {
  50. return
  51. }
  52. return
  53. }