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
'Back-End > Node.js' 카테고리의 다른 글
[NodeJS] Socket.IO란? (1) | 2025.03.07 |
---|---|
[NodeJS] Node.js를 활용한 애니메이션 API 만들기 (1) | 2025.03.03 |
[NodeJS] 9장(완) 추가 학습하기 (0) | 2025.03.03 |
[NodeJs] 8장 Docker(도커)를 사용한 배포 (0) | 2025.03.02 |
[NodeJS] 7장 에러처리 (0) | 2025.02.27 |