Programming/GoLang

[2] Go Lang, HTTP 서버 구현 및 JSON 데이터 처리

Allen93 2025. 2. 3. 15:18

1️⃣ 간단한 HTTP 서버 구현

Go의 net/http 패키지를 사용해 HTTP 서버를 간단히 구현할 수 있습니다.

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Welcome to GoLang Server!")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}
  • 결과: 브라우저에서 http://localhost:8080로 접속 시 "Welcome to GoLang Server!" 출력.

2️⃣ JSON 데이터 처리

Go의 encoding/json 패키지를 사용해 JSON 데이터를 처리합니다.

package main

import (
    "encoding/json"
    "fmt"
)

type User struct {
    Name  string `json:"name"`
    Email string `json:"email"`
}

func main() {
    jsonData := `{"name": "John", "email": "john@example.com"}`
    var user User
    json.Unmarshal([]byte(jsonData), &user)
    fmt.Printf("Name: %s, Email: %s\n", user.Name, user.Email)
}

 


3️⃣ 파일 처리

Go에서는 파일 읽기와 쓰기가 간단하게 구현됩니다.

package main

import (
    "fmt"
    "os"
)

func main() {
    file, err := os.Create("example.txt")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    defer file.Close()

    file.WriteString("Hello, Go!")
    fmt.Println("File created successfully.")
}

https://github.com/siilver94/GoLang?tab=readme-ov-file

 

GitHub - siilver94/GoLang

Contribute to siilver94/GoLang development by creating an account on GitHub.

github.com

 

728x90