Go

return

client, err := net.DialTimeout(netScheme, host, time.Duration(w.Timeout))
if err != nil {
    fmt.Printf("Error: %v\n", err)
} else {
    fmt.Printf("Connected to %v\n", client.RemoteAddr())
}

자바로 치면,

// Java에서 다중 반환 값을 처리하는 예시

// 사용자 정의 클래스
class ConnectionResult {
    public Socket client;
    public Exception error;
    
    public ConnectionResult(Socket client, Exception error) {
        this.client = client;
        this.error = error;
    }
}

public ConnectionResult connect(String host, int timeout) {
    try {
        Socket client = new Socket();
        client.connect(new InetSocketAddress(host, timeout));
        return new ConnectionResult(client, null);
    } catch (IOException e) {
        return new ConnectionResult(null, e);
    }
}

// 사용 예시
ConnectionResult result = connect("example.com", 1000);
if (result.error != null) {
    System.out.println("Error: " + result.error.getMessage());
} else {
    System.out.println("Connected to " + result.client.getRemoteSocketAddress());
}

for loop

go

// w.hosts 슬라이스가 있다고 가정
for _, host := range w.hosts {
    // 여기서 host 변수는 w.hosts의 현재 요소입니다.
    fmt.Println("Connecting to:", host)
}

java

// hosts 리스트가 있다고 가정
List<String> hosts = Arrays.asList("host1", "host2", "host3");
for (String host : hosts) {
    // 여기서 host 변수는 hosts 리스트의 현재 요소입니다.
    System.out.println("Connecting to: " + host);
}

Go 튜토리얼

https://go.dev/doc/tutorial

Getting Started

Create a Go module

// 변수 선언 and 초기화 방법1
var message string
message = fmt.Sprintf("Hi, %v. Welcome!", name)

// 변수 선언 and 초기화 방법2
message := fmt.Sprintf("Hi, %v. Welcome!", name)

Call your code from another module

<home>/
 |-- greetings/ (호출받는 패키지)
 |-- hello/ (호출하는 패키지)
module example.com/hello

go 1.22.5

replace example.com/greetings = >../greetings

Return and handle an error

질문: name에 nil 넣으면 어떻게 되나요? 답변: Go 언어에서 string 타입은 기본적으로 nil이 아닌 빈 문자열 ""로 초기화됩니다. 즉, string 타입 변수는 nil 값을 가질 수 없으며, 초기화되지 않은 상태에서는 빈 문자열로 간주됩니다.

질문: string말고 어떤 타입이있고 어떤 기본값을 같나? 모두 nil 을 가질수없나? 답변: 타입에는 기본타입과 기본타입이 있다

아래꺼는 다른 문서로..

	1.	기본 타입
	•	bool: 기본값은 false
	•	string: 기본값은 "" (빈 문자열)
	•	정수 타입: int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr: 기본값은 0
	•	부동 소수점 타입: float32, float64: 기본값은 0.0
	•	복소수 타입: complex64, complex128: 기본값은 0+0i
	2.	기타 타입
	•	배열: 모든 요소가 타입의 기본값으로 초기화된 배열
	•	슬라이스: nil
	•	맵: nil
	•	포인터: nil
	•	채널: nil
	•	함수: nil
	•	인터페이스: nil
	•	구조체: 모든 필드가 타입의 기본값으로 초기화된 구조체
package main

import "fmt"

func main() {
	var b bool
	var s string
	var i int
	var f float64
	var c complex128
	var a [3]int
	var p *int
	var sl []int
	var m map[string]int
	var ch chan int
	var fn func() int
	var iface interface{}

	fmt.Printf("bool: %v\n", b)
	fmt.Printf("string: %v\n", s)
	fmt.Printf("int: %v\n", i)
	fmt.Printf("float64: %v\n", f)
	fmt.Printf("complex128: %v\n", c)
	fmt.Printf("array: %v\n", a)
	fmt.Printf("pointer: %v\n", p)
	fmt.Printf("slice: %v\n", sl)
	fmt.Printf("map: %v\n", m)
	fmt.Printf("channel: %v\n", ch)
	fmt.Printf("function: %v\n", fn)
	fmt.Printf("interface: %v\n", iface)
}
bool: false
string: 
int: 0
float64: 0
complex128: (0+0i)
array: [0 0 0]
pointer: <nil>
slice: []
map: map[]
channel: <nil>
function: <nil>
interface: <nil>

Return a random greeting

목적

변수, 함수, 타입의 이름

슬라이스와 배열

var arr [3]int // 크기가 3인 int 배열 선언
arr = [3]int{1, 2, 3} // 배열 초기화
fmt.Println(arr) // 출력: [1 2 3]

s := []int{1, 2, 3} // int 슬라이스 선언 및 초기화
s = append(s, 4) // 슬라이스에 요소 추가
fmt.Println(s) // 출력: [1 2 3 4]

Return greetings for multiple people

목표

질문: Go 언어에서 make() 뭐지? messages := make(map[string]string)

// 맵 초기화
messages := make(map[string]string)

// 슬라이스 초기화
numbers := make([]int, 5) // 길이가 5인 슬라이스 생성
numbers := make([]int, 5, 10) // 길이가 5이고 용량이 10인 슬라이스 생성

// 채널 생성 (채널은 데이터 송수신 담당)
ch := make(chan int)

Add a test

Go tcp client 코드 예제

func SendCloudWatch(cloudwatch model.AwsRdsCloudWatch) {
    // ... 생략

	conn, err := net.Dial("tcp", fmt.Sprintf("%s:%s", host, portStr))
	if err != nil {
		logger.Error("Failed to connect to TCP server:", err)
		return
	}
	defer conn.Close()

	if err := send(conn, data.ToByteArray()); err != nil {
		logger.Error("Failed to send data:", err)
	}
}

defer 는 예약하는 역할.

func send(conn net.Conn, data []byte) error {
	const writeTimeout = 5 * time.Second
	totalBytesSent := 0

	for totalBytesSent < len(data) {
		writeDeadline := time.Now().Add(writeTimeout)
		if err := conn.SetWriteDeadline(writeDeadline); err != nil {
			return fmt.Errorf("failed to set write deadline: %v", err)
		}
		bytesSent, err := conn.Write(data[totalBytesSent:])
		if err != nil {
			return fmt.Errorf("failed to send data: %v", err)
		}
		totalBytesSent += bytesSent
	}
	return nil
}

defer

Go의 defer

자바랑 비교

예제

명령어

cd path/to/go-project

# Go 바이너리를 Amazon Linux 2023 및 ARM64용으로 빌드
GOOS=linux GOARCH=arm64 go build -o bootstrap main.go

# 실행 권한을 추가
chmod +x bootstrap

# 실행 파일을 압축
zip function.zip bootstrap
GOOS=linux GOARCH=amd64 go build -o main .