rest.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. package restapi
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "git.wecise.com/wecise/common/rest"
  6. )
  7. func Request(method, url, body string) (map[string]any, error) {
  8. var fm *rest.ReqForm = &rest.ReqForm{
  9. Username: "wecise.admin",
  10. Password: "admin",
  11. Timeout: 60, // 整个请求的超时时间,秒(包含连接、写入、读取)
  12. Body: body,
  13. ContentType: "application/json;charset=UTF-8",
  14. Transport: nil,
  15. }
  16. b, err := rest.Request(method, url, fm)
  17. if err != nil {
  18. return nil, fmt.Errorf("request %s %s error: %v", url, method, err)
  19. }
  20. res := make(map[string]any)
  21. if b[0] == '{' {
  22. if err = json.Unmarshal(b, &res); err != nil {
  23. return nil, fmt.Errorf("unmarshal response json error: %v", err)
  24. }
  25. switch res["status"].(type) {
  26. case string:
  27. if res["status"] != "ok" {
  28. return nil, fmt.Errorf("%s %s response status error: \n%s", url, method, string(b))
  29. }
  30. default:
  31. }
  32. } else {
  33. return nil, fmt.Errorf("%s %s response error: %s", url, method, string(b))
  34. }
  35. return res, nil
  36. }