使用 Project IDX 和 Gemini API 构建 Go 应用

十二月 18, 2024
Suzy Mueller Software Engineer
Nooras Saba Engineering Manager

Project IDX 于 2024 年 6 月推出,是一个用于云端全栈应用开发的 AI 辅助工作区,支持各种框架、语言和服务,以及与 Google 产品的集成以简化开发工作流。

我们将利用 Project IDX 向您展示如何在几分钟内使用 Go 构建应用。我们将在 Project IDX 中设置 Go 开发环境,并创建您的首个服务器应用。我们将介绍如何在 IDX 中设置 Go 开发环境并创建简单的 Hello World 服务器。

在 IDX 中创建工作区有几种不同的方法。您可以导入 GitHub 代码库,从头开始创建新的空白工作区,或使用预配置模板。我们将首先向您展示如何从零开始,然后我们再了解各种模板


开始构建

本部分将介绍如何使用 IDX 设置环境并编写基本的 Hello World 服务器。

首先,我们从 idx.google.com/new/blank 的 IDX 中创建一个新的空白项目。此项目包含一个自述文件和一个默认的 dev.nix


环境自定义

您可以使用 nix 环境配置对环境配置进行自定义。IDX 中 Go 工作区的最小配置将添加 Go nix 软件包并安装 Go 扩展程序:

更新 .idx/dev.nix,使其包含 Go nix 软件包和 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