Membangun aplikasi Go menggunakan Project IDX dan Gemini API

DES 18, 2024
Suzy Mueller Software Engineer
Nooras Saba Engineering Manager

Project IDX yang diluncurkan pada Juni 2024 merupakan ruang kerja berbasis AI untuk pengembangan aplikasi full-stack di cloud. Ia mendukung berbagai macam framework, bahasa, dan layanan, serta integrasi dengan produk Google untuk menyederhanakan alur kerja pengembangan.

Kami akan memanfaatkan hal ini untuk menunjukkan kepada Anda cara membangun aplikasi dengan Go dalam hitungan menit. Kita akan menyiapkan lingkungan pengembangan Go di Project IDX dan membuat aplikasi server pertama Anda. Mari kita pelajari cara menyiapkan lingkungan pengembangan Go di IDX dan membuat server halo dunia sederhana.

Ada beberapa cara untuk membuat ruang kerja di IDX. Anda bisa mengimpor repositori GitHub, membuat ruang kerja kosong baru dari awal, atau menggunakan template yang telah dikonfigurasi sebelumnya. Kami akan menunjukkan kepada Anda cara memulai dari awal terlebih dahulu, kemudian kita akan mempelajari template


Memulai

Bagian ini akan menjelaskan penyiapan lingkungan dan penulisan server Halo Dunia dasar dengan IDX.

Mari kita mulai dengan membuat project kosong baru di IDX dari idx.google.com/new/blank. Project ini berisi README dan dev.nix default.


Penyesuaian Lingkungan

Konfigurasi lingkungan bisa disesuaikan dengan konfigurasi lingkungan nix. Konfigurasi minimal untuk ruang kerja Go di IDX akan menambahkan paket nix Go dan menginstal ekstensi Go:

Update .idx/dev.nix untuk menyertakan paket nix Go dan ekstensi Go:

{ pkgs, ... }: {
  packages = [
    pkgs.go
  ];
 
  idx = {
    extensions = [
      "golang.go"
    ];
  };
}

Rebuild your environment to allow these changes to take effect.


Write Go code

Now that the workspace is set up for Go code development, we can start writing our Go server.

First, let's initialize the module that will contain our Go code. You can do this by running the > Go: Initialize go.mod provided by the Go extension from the Command Palette, or by running go mod init from the command line.

$ go mod init github.com/myorg/helloWorld

Let’s create a main.go with a simple server that returns “Hello, World!"

package main
 
import (
	"fmt"
	"log"
	"net/http"
	"os"
)
 
func main() {
	log.Print("starting server...")
	http.HandleFunc("/", handler)
 
	// Determine port for HTTP service.
	port := os.Getenv("PORT")
	if port == "" {
		port = "3000"
		log.Printf("defaulting to port %s", port)
	}
 
	// Start HTTP server.
	log.Printf("listening on port %s", port)
	if err := http.ListenAndServe(":"+port, nil); err != nil {
		log.Fatal(err)
	}
}
 
func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "<!DOCTYPE html>\n")
	fmt.Fprint(w, "Hello, World!\n")
}

Preview in IDX

Now that we have a server that can listen to requests, let’s test it out by creating a preview.

To .idx/dev.nix, add the web preview configuration:

idx = {
      previews = {
      enable = true;
      previews = {
          web = {
          command = ["go" "run" "main.go"];
          manager = "web";
          env = {
            # Environment variables to set for your server
            PORT = "$PORT";
          };
        };
      };
    };
  };

Rebuild the environment again to see the web preview. The preview can also be opened from the Command Palette using > Project IDX: Show Web Preview.

Show Web Preview in Project IDX

Explore Go Templates in IDX

To start quickly, we are providing you with ready to use templates that include a pre-configured environment with all the tools and the libraries needed.

Start with one of the Go backend server templates or start building LLM applications with the Go and Gemini template.

Gemini with Go template is integrated with Gemini API to leverage the power of AI. Plug in your Gemini API key to get going.

Code editor displays project files and a web page titled "Baking with Gemini"  with images of baked goods and a prompt to provide a recipe in IDX