erlang各种有用的函数包括一些有用nif封装,还有一些性能测试case。
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.6 KiB

  1. -module(utHttpOn).
  2. %% API
  3. -export([
  4. req/6, %% Post, Put, Delete Only
  5. req_get/3, %% Get Only
  6. url_encode/1
  7. ]).
  8. -export([get_unique_ref/1, get_conv_ref/0]).
  9. get_conv_ref() ->
  10. get_unique_ref(20).
  11. get_unique_ref(Length) ->
  12. IntPass = random_num(36, Length),
  13. list_to_binary(lists:flatten(io_lib:format("~.36B", [IntPass]))).
  14. random_num(NumeralSystemBase, Length) ->
  15. Min = round(math:pow(NumeralSystemBase, Length - 1)),
  16. Max = round(math:pow(NumeralSystemBase, Length)),
  17. rand:uniform(Min, Max).
  18. req(Method, Url, Headers, ContType, Body, HttpOpts)
  19. when Method == post orelse Method == put orelse Method == delete ->
  20. HttpClOpts = [{sync, true}, {body_format, binary}],
  21. Resp = httpc:request(Method, {eu_types:to_list(Url), Headers, ContType, Body}, HttpOpts, HttpClOpts),
  22. minimize_resp(Resp).
  23. req_get(Url, Headers, HttpOpts) ->
  24. HttpClOpts = [{sync, true}, {body_format, binary}],
  25. Resp = httpc:request(get, {eu_types:to_list(Url), Headers}, HttpOpts, HttpClOpts),
  26. minimize_resp(Resp).
  27. minimize_resp(Resp) ->
  28. case Resp of
  29. {ok, {{_NewVrsn, 200, _}, _Headers, RespBody}} ->
  30. {ok, 200, RespBody};
  31. {ok, {{_NewVrsn, HttpCode, _}, _Headers, RespBody}} ->
  32. {error, HttpCode, RespBody};
  33. Any -> Any
  34. end.
  35. url_encode(Data) ->
  36. url_encode(Data, "").
  37. url_encode([], Acc) ->
  38. Acc;
  39. url_encode([{Key, Value} | R], "") ->
  40. url_encode(R, edoc_lib:escape_uri(Key) ++ "=" ++ edoc_lib:escape_uri(Value));
  41. url_encode([{Key, Value} | R], Acc) ->
  42. url_encode(R, Acc ++ "&" ++ edoc_lib:escape_uri(Key) ++ "=" ++ edoc_lib:escape_uri(Value)).