Http Server in Fortran

Here’s the translation of the HTTP server example from Go to Fortran, along with explanations in Markdown format suitable for Hugo:

! Writing a basic HTTP server in Fortran requires external libraries.
! This example uses the 'http' module from the 'fortran-http' library.

module http_server
  use iso_fortran_env, only: error_unit
  use http, only: http_server, http_request, http_response
  implicit none

contains

  ! A fundamental concept in HTTP servers is handlers. A handler is a
  ! subroutine that processes incoming requests and generates responses.

  subroutine hello(req, res)
    type(http_request), intent(in) :: req
    type(http_response), intent(inout) :: res

    ! Subroutines serving as handlers take an http_request and an
    ! http_response as arguments. The response is used to fill in the
    ! HTTP response. Here our simple response is just "hello\n".

    call res%send_string("hello\n")
  end subroutine hello

  subroutine headers(req, res)
    type(http_request), intent(in) :: req
    type(http_response), intent(inout) :: res
    character(len=:), allocatable :: header_name, header_value

    ! This handler does something a little more sophisticated by reading
    ! all the HTTP request headers and echoing them into the response body.

    do while (req%get_next_header(header_name, header_value))
      call res%send_string(header_name // ": " // header_value // "\n")
    end do
  end subroutine headers

  subroutine run_server()
    type(http_server) :: server
    integer :: stat

    ! We register our handlers on server routes using the add_route method.
    ! It takes a path and a subroutine as arguments.

    call server%add_route("/hello", hello)
    call server%add_route("/headers", headers)

    ! Finally, we call the listen method with the port to start the server.

    stat = server%listen(8090)
    if (stat /= 0) then
      write(error_unit, *) "Failed to start server"
    end if
  end subroutine run_server

end module http_server

program main
  use http_server
  implicit none

  call run_server()
end program main

To run the server:

$ gfortran -o http_server http_server.f90 -lfortran-http
$ ./http_server &

Access the /hello route:

$ curl localhost:8090/hello
hello

This Fortran example demonstrates how to create a basic HTTP server using the ‘fortran-http’ library. It includes two handlers: one for a simple “hello” response and another that echoes the request headers.

Note that Fortran doesn’t have built-in HTTP server capabilities, so we’re using an external library. The concepts are similar to other languages, but the implementation details may vary depending on the specific library used.

The program defines a module http_server that contains the handler subroutines and a run_server subroutine to set up and start the server. The main program simply calls run_server to start the HTTP server.

Remember to install and link against the ‘fortran-http’ library when compiling this program.