request.go 573B

12345678910111213141516171819202122232425262728293031323334
  1. package request
  2. import (
  3. "bytes"
  4. "errors"
  5. "io"
  6. "net/http"
  7. )
  8. func post(url string, contentType string, body []byte) ([]byte, error) {
  9. resp, e1 := http.Post(url, contentType, bytes.NewReader(body))
  10. if e1 != nil {
  11. return nil, e1
  12. }
  13. if resp.StatusCode > 299 {
  14. return nil, errors.New(resp.Status)
  15. }
  16. body, e2 := io.ReadAll(resp.Body)
  17. resp.Body.Close()
  18. if e2 != nil {
  19. return nil, e2
  20. }
  21. return body, nil
  22. }
  23. // PostJSON 使用 POST 方式发送 json 数据
  24. func PostJSON(url string, body []byte) ([]byte, error) {
  25. return post(url, ContentTypeJSON, body)
  26. }