-- Leo's gemini proxy

-- Connecting to ibannieto.info:1965...

-- Connected

-- Sending request

-- Meta line: 20 text/gemini;lang=en

Creating a cgi-bin with golang


Hi ya 👋


I'm going to create a cgi-bin called "iss" with golang, only for fun.


My plan is to get the ISS coordinates and the number of people aboard.


All data is collected from OpenNotify:


OpenNotify


This is the code:


package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
)

type Response struct {
	Message     string `json:"message"`
	Timestamp   int    `json:"timestamp"`
	IssPosition struct {
		Latitude  string `json:"latitude"`
		Longitude string `json:"longitude"`
	} `json:"iss_position"`
}

func main() {
	fmt.Println("20 text/gemini")
	fmt.Println("```")

	fmt.Println("ISS Coordinates:")
	res, err := http.Get("http://api.open-notify.org/iss-now.json")
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		log.Fatal(err)
	}

	var result Response
	if err := json.Unmarshal(body, &result); err != nil { // Parse []byte to the go struct pointer
		fmt.Println("Can not unmarshal JSON")
	}

	latitude := result.IssPosition.Latitude
	longitude := result.IssPosition.Longitude

	fmt.Println("Latitude:", latitude)
	fmt.Println("Longitude:", longitude)
}

Yeah, I ken that the code is very simple and stupid but I just want to play with golang and cgi-bin files 😅


Compile and run the source code:


go build -o iss iss.go ; ./iss

In order to move the cgi to production, it's recommended to strip (delete debug info) and compress the compiled file. You'll need the upx packer:


strip ./iss ; upx ./iss

In my case the file was reduced from 4.4Mb to 1.8Mb


Try it!


International Space Station Current Location:
Latitude: -41.1457
Longitude: -22.4292

How Many People Are In Space Right Now: 10

Well, the number of people in space right now is not only aboard in the ISS but in the space 🧐 The API that I'm using returns the current number of people in space. When known it also returns the names and spacecraft those people are on.


Creating a cgi-bin with golang was published on 📅 2022-06-17


back


CC-BY-SA 4.0

-- Response ended

-- Page fetched on Tue May 21 11:31:41 2024