Http Client in Fortran
Here’s the translation of the HTTP Client example from Go to Fortran, formatted in Markdown suitable for Hugo:
Our example demonstrates how to make HTTP requests in Fortran using the http
module from the Fortran Net library. We’ll use it to issue simple HTTP requests.
program http_client
use http
use iso_fortran_env, only: error_unit
implicit none
type(http_response) :: response
type(http_client) :: client
integer :: i
character(len=1024) :: line
! Issue an HTTP GET request to a server
response = client%get("https://gobyexample.com")
if (response%status /= 200) then
write(error_unit,*) "Error: ", response%status
stop
end if
! Print the HTTP response status
print *, "Response status: ", response%status
! Print the first 5 lines of the response body
do i = 1, 5
if (response%body%read_line(line) /= 0) exit
print *, trim(line)
end do
! Clean up
call response%destroy()
call client%destroy()
end program http_client
To run the program, compile it with a Fortran compiler that supports the Fortran Net library, and then execute the resulting binary:
$ gfortran -o http_client http_client.f90 -lfortran-net
$ ./http_client
Response status: 200
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Go by Example</title>
This Fortran program demonstrates basic HTTP client functionality:
We use the
http
module from the Fortran Net library to handle HTTP operations.We create an
http_client
object to manage the HTTP connection.We use the
get
method of the client to send a GET request to “https://gobyexample.com”.We check the response status and print it.
We then read and print the first 5 lines of the response body.
Finally, we clean up by destroying the response and client objects.
Note that Fortran’s approach to HTTP operations is more explicit compared to some other languages. The Fortran Net library provides a way to perform these operations, but it may not be as integrated into the standard library as in some other programming languages.
Also, error handling in Fortran is typically done through status codes or explicit error variables, rather than exceptions as in some other languages.