[NodeJS] Go와 Nodejs 연결하기

1. Go 서버 설정

Go와 Node.js를 연결하려면 여러 방법이 있지만, 일반적으로는 두 언어 간의 통신은 HTTP API를 통해 이루어집니다. 먼저 Go로 간단한 HTTP 서버를 생성합니다.

package main

import (
	"encoding/json"
	"net/http"
)

type Cat struct {
	Name string `'json:"name"`
	Age int `json:"age"`
}

func catsHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodGet {
	  cats := []Cat{
		{Name: "Koras02", Age: 27},
		{Name: "PiPi", Age: 22},
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(cats)
   } else {
       http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
   }
}

func main() {
	http.HandleFunc("/cats", catsHandler)
	http.ListenAndServe(":8080", nil)
}

 

위 코드는 /cats 엔드포인트에서 고양이 정보를 반환하는 간단한 HTTP 입니다. 아래 명령어로 go 서버를 실행합니다.

go run main.go

2. Node.js 클라이언트 설정

Node.js에서 Go 서버에 요청을 보내는 클라이언트를 설정합니다.

mkdir my-node-client
cd my-node-client
npm init -y
npm install axios

 

Node.js 세팅 후 폴더내 index.js를 생성해서 아래 코드를 작성합니다.

const axios = require("axios");

async function fetchCats() {
  try {
    const response = await axios.get("http://localhost:8080/cats");
    console.log(response.data);
  } catch (error) {
    console.error("Error fetching cats:", error);
  }
}

fetchCats();

 

아래 명령어로 Node.js를 실행합니다.

node index.js

 

Node.js 클라이언트를 실행하면 Go 서버에서 반환한 고양이 목록이 출력됩니다.


 

 

GitHub - Koras02/nodejs-gohttp

Contribute to Koras02/nodejs-gohttp development by creating an account on GitHub.

github.com

 

LIST