..

Ocaml 技巧

  1. 静态编译一个 Ocaml 脚本文件
ocamlopt -ccopt -static -o hello hello.ml

dune 项目静态编译可以参考 https://www.ocamlpro.com/2021/09/02/generating-static-and-portable-executables-with-ocaml/

(executable 
(flags (:standard -cclib -static))
(name main))
  1. 相同目录下的文件直接当成模块使用 hello.ml 在本目录的其他文件中,可以直接 Open hello

  2. Ocaml 发送 post 请求,并且设置 header 和 body

open Lwt

let body =
  let buffer =
    Cohttp_lwt.Body.of_string "body string"
  in
  let headers = Cohttp.Header.init () in
  Cohttp_lwt_unix.Client.post ~body:buffer
    ~headers:(Cohttp.Header.add headers "Content-type" "application/json")
    (Uri.of_string
       "http://.........")
  >>= fun (_, body) -> Cohttp_lwt.Body.to_string body

let () =
  let body = Lwt_main.run body in
  print_endline ("Received body\n" ^ body)

设置 dune 文件如下

(executable 
(name post)
(libraries core cohttp   cohttp-lwt-unix))

参考文章:

1. https://www.systutorials.com/how-to-statically-link-ocaml-programs/