DEV Community

kyorohiro (kiyohiro kawamura)
kyorohiro (kiyohiro kawamura)

Posted on • Updated on

CGI at Clang and Dart (1)

Nowadays, when creating a dynamic homepage, "Launch a Linux instance on VPS", "Distribute contents using Serverless framework", "K8S etc. I think it's a recent trend.

Until very recently, however, it was common to rent a server space and use CGI to deliver dynamic content.
I will explain about this CGI with Dart.

CGI at Clang and Dart

Also, Perl and PHP are often used for CGI, But In This Document, C language and Dart language are targeted.

CGI is So Simple

Compared with recent Serverless such as React Vue Flutter and Lambda with Firebase
I think it was because it was easy to learn.

What is CGI

CGI stands for Common Gateway Interface.

Especially, it decides the communication method between the server and the external program.
It is super simple unlike the current Interface.

Sample

Hello,World!! at Clang

// hello.c
// gcc hello.c -o hello.cgi
#include<stdio.h>

int main(int argc, char* argv[]) {
    printf("Content-type: text/html\n\n");
    printf("Hello,World!!\n");
    return 0;
}

Enter fullscreen mode Exit fullscreen mode

This is Hello World Application for CGI
This app, when you enter the command ./hello.cgi,

"""
Content-type: text/html

Hello,World!!
"""

And, it is an application that only displays the character string on the console.

Become Hello World Webpage

And This Application Become Hello World Webpage

If you call "http://example.com/hello.cgi" from your browser,
"Hello, World!!" is displayed in the browser.

Call the app from the server like this
With CGI, you can return the output from the application to the user.

Let's try

I created docker environment for this dart's cgi document

Start Container

$ git clone https://github.com/kyorohiro/dartlang_cgi.git
$ cd ./dartlang_cgi/001
$ docker-compose build
$ docker-compose up -d
Enter fullscreen mode Exit fullscreen mode

Open VSCODE on Docker

Start VSCode

open vscode on browser.
http://127.0.0.1:8443
※ 127.0.0.1 is your docker host

and start apache server in vscode

$ apache2
Enter fullscreen mode Exit fullscreen mode

build cgi

$ cd /app/www/cgi
$ gcc hello.c -o hello.cgi
$ dart2native hello_dart.dart -o hello_daet.cgi
Enter fullscreen mode Exit fullscreen mode

test cgi

open http://127.0.0.1:8080/ then ./app/www/index.html
open http://127.0.0.1:8080/cgi-bin/hello.cgi then execute ./app/cgi/hello.cgi application

PS

Dart's code is following

main(List<String> args) {
  print("Content-type: text/html\n\n");
  print("Hello,World From Dart!!\n");
  return 0;
}
Enter fullscreen mode Exit fullscreen mode

All Codes

https://github.com/kyorohiro/dartlang_cgi

Next Time

GET or POST or Cookie or DB

Top comments (1)

Collapse
 
kyorohiro profile image
kyorohiro (kiyohiro kawamura)

"GET or POST or Cookie or DB " 's code is in github.com/kyorohiro/dartlang_cgi