Sunday, March 2, 2025

Golf 273 released

  • Fixed two bugs that prevented compilation of Golf program in some cases. The issues were introduced in version 265.
  • Set proper permissions on pcre2* files for packaging

Saturday, March 1, 2025

Web framework for C programming language

Golf has an "extended" mode, which allows for C code to be used directly. Normally, this is not allowed, but if you use extended-mode statement in your .golf file, then you can call C code from it.

In extended mode, Golf is effectively a web framework for C programming language; read this for more about implications on memory safety.

Here's the example of using Golf as a web framework for C. In this case it's a simple C function to calculate the factorial of a a number. Then we'll expose this functionality in an equally simple web application.
Create the Golf application
mkdir -p c-for-web
cd c-for-web

Create "fact" application ("-k"):
gg -k fact

Save the following into a file "calc-fact.golf". This is the web service which will interact with web clients (such as browsers); it will also call the C function we'll create a bit further below:
 extended-mode // extended mode in order to call C code

 %% /calc-fact public
     get-param par // get input parameter from URL
     string-number par to num // convert to number
     set-number result
     call-extended factorial(num, &result) // call C function
     // Output result
     @Factorial of <<p-out par>> is <<p-num result>>
 %%

Add C code to Golf application
Next, create C file "factorial.c". This is the C function we're calling from Golf code above:
 #include "golf.h"

 // Compute factorial of f, and store result into res
 void factorial(gg_num f, gg_num *res)
 {
     *res = 1;
     gg_num i;
     for (i = 2; i <= f; i++) {
         *res *= i;
     }
 }