Go로 Google Cloud Function 배포하기

지니🧸·2024년 2월 1일
0

클라우드 컴퓨팅

목록 보기
2/2

Google Cloud 웹사이트(?)에서 inline code editor로 하는 방법도 있지만.. 나는 인라인 코드 에디터가 불편해서 로컬에서 배포했다

본인은 맥OS 기준

1. Google Cloud SDK CLI 설치

로컬에서 하려면 로컬에 설치해야 한다
서버에서 돌리는거면 스킵

(1) 구글 클라우드 프로젝트가 생성되어있는지 확인

없으면 만들면됨

(2) 프로젝트에 결제 허용되어있는지 확인

돈 빠져나갈 수도 있다는 소리

(3) Python 버전 확인

python3 -V
python -V

Google Cloud SDK를 사용하려면 파이썬 3.8~3.12여야 한다
나는 3.11 이였는데 어차피 메인 설치 스크립트가 파이썬 다운로드 받을거냐고 프롬프트 띄어주더라

(4) 패키지 다운로드

macOS 64-bit (ARM64, Apple M1 silicon)

(5) 원하는 위치에 패키지 zip 풀기

(6) 설치 완료하기

./google-cloud-sdk/install.sh

(7) gcloud CLI 초기화

./google-cloud-sdk/bin/gcloud init
gcloud init

(8) 구글 로그인

구글 로그인하라는 프롬프트 뜨면 계정으로 로그인하면됨

(9) 프로젝트 선택

...

2. 함수 만들기

(1) 폴더(helloworld/) 만들기

mkdir ~/helloworld
cd ~/helloworld

(2) 방금 만든 폴더(helloworld/) 안에 go 파일 쓰기


// Package helloworld provides a set of Cloud Functions samples.
package helloworld

import (
        "encoding/json"
        "fmt"
        "html"
        "net/http"

        "github.com/GoogleCloudPlatform/functions-framework-go/functions"
)

func init() {
        functions.HTTP("HelloHTTP", HelloHTTP)
}

// HelloHTTP is an HTTP Cloud Function with a request parameter.
func HelloHTTP(w http.ResponseWriter, r *http.Request) {
        var d struct {
                Name string `json:"name"`
        }
        if err := json.NewDecoder(r.Body).Decode(&d); err != nil {
                fmt.Fprint(w, "Hello, World!")
                return
        }
        if d.Name == "" {
                fmt.Fprint(w, "Hello, World!")
                return
        }
        fmt.Fprintf(w, "Hello, %s!", html.EscapeString(d.Name))
}

(3) 의존성 추가

cd ~/helloworld
go mod init example.com/hello
go mod tidy

(4) 로컬(helloworld/)에서 함수 빌드/테스트해보기

cd ~/helloworld
go mod init example.com/hello
go mod tidy

(5) helloworld/cmd/에 main.go 쓰기

package main

import (
  "log"
  "os"

  // Blank-import the function package so the init() runs
  _ "example.com/hello"
  "github.com/GoogleCloudPlatform/functions-framework-go/funcframework"
)

func main() {
  // Use PORT environment variable, or default to 8080.
  port := "8080"
  if envPort := os.Getenv("PORT"); envPort != "" {
    port = envPort
  }
  if err := funcframework.Start(port); err != nil {
    log.Fatalf("funcframework.Start: %v\n", err)
  }
}

새로 추가한 의존성이 확인 불가하다는 에러 뜨면 터미널에

go get <의존성>

(6) 의존성 다시 확인

go mod tidy

(7) 함수 로컬에서 런

export FUNCTION_TARGET=HelloHTTP
go run ~/helloworld/cmd/main.go

(8) http://localhost:8080 방문으로 테스트

3. 배포하기

helloworld/에서 다음 명령어 입력

  gcloud functions deploy go-http-function \
    --gen2 \
    --runtime=go121 \
    --region=REGION \
    --source=. \
    --entry-point=HelloHTTP \
    --trigger-http \
    --allow-unauthenticated

REGION에는 본인 프로젝트의 리전을 넣으면된다 (예) us-west1, us-central1
--allow-unauthenticated 설정으로 로그인 등 없이 접근 가능

빌드 잘 됐는지는 터미널에 결과로도 뜬다

4. 배포한 함수 테스트하기

gcloud functions describe go-http-function --region=REGION

요 명령어로 uri 값을 받아서 방문해보면된다

+) 환경변수 설정하기

런타임 환경변수 설정이 필요했음

환경변수 추가하기

(1) 환경변수 하나 설정하기

gcloud functions deploy go-http-function --set-env-vars FOO=bar FLAGS 

(2) 환경변수 두개 이상 설정하기

콤마로 구분한다

gcloud functions deploy go-http-function --set-build-env-vars FOO=bar,BAZ=boo

(3) 환경변수 파일로 설정하기

디렉토리 안에 .yaml 등 파일을 만들어서 환경변수로 사용하는 것

gcloud functions deploy go-http-function --set-env-vars FOO=bar,BAZ=boo

config.yaml은 다음과 비슷하게 쓰면 됨

SERVICE_KEY: "HELLOOSLDFJSLDFJLKSDF"
URL: "https://hellohello.com/"

모든 value 값은 string이여야 함

go코드에서는 os.Getenv("환경변수 키 값")으로 가져다 쓰면됨
(ex) os.Getenv("SERVICE_KEY")

환경변수 업데이트하기

(1) 하나 업데이트하기

gcloud functions deploy go-http-function --update-env-vars FOO=bar

(2) 두개 이상 업데이트하기

gcloud functions deploy go-http-function --update-env-vars FOO=bar,BAZ=boo

https://cloud.google.com/sdk/docs/install-sdk
https://cloud.google.com/functions/docs/create-deploy-http-go
https://cloud.google.com/functions/docs/configuring/env-var

profile
우당탕탕

0개의 댓글