2026년 상식닷컴 선정 식당 & 카페 리스트
최근에 오픈한 호텔을 찾는다면 살펴보세요

Go에서 HTTP 서버를 만드는 방법은 무엇인가요?

_____
Q1: Go에서 기본적인 HTTP 서버를 만드는 방법은 무엇인가요?
A1: `net/http` 패키지를 사용하여 간단히 HTTP 서버를 만들 수 있습니다. 예를 들어:

```go
package main

import (
"fmt"
"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
}

func main() {
http.HandleFunc("/", handler) // URL 경로와 핸들러 함수 연결
http.ListenAndServe(":8080", nil) // 포트 8080에서 서버 시작
}
```
이 코드는 기본 경로 `/`에 접속할 때 "Hello, World!"를 응답하는 서버입니다.

---

Q2: `http.HandleFunc`와 `http.Handle`의 차이는 무엇인가요?
A2:
- `http.HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))`는 함수 타입 핸들러를 패턴에 등록합니다. 내부적으로 `http.HandlerFunc` 타입으로 변환하여 사용합니다.
- `http.Handle(pattern string, handler http.Handler)`는 `http.Handler` 인터페이스를 구현한 값을 등록합니다.
간단한 함수 핸들러는 `http.HandleFunc`를, 복잡한 핸들러나 구조체로 구현된 핸들러는 `http.Handle`을 사용합니다.

---

Q3: `http.ListenAndServe` 함수의 역할은 무엇인가요?
A3: `http.ListenAndServe(addr string, handler http.Handler)`는 지정한 주소(addr)와 포트에서 HTTP 서버를 시작합니다. 두 번째 인자에 `nil`을 넘기면 기본 디폴트 `http.DefaultServeMux`를 사용합니다. 블로킹 함수이므로 서버가 종료되지 않는 한 계속 동작합니다. 에러가 발생하면 반환합니다.

---

Q4: 요청 경로마다 다른 핸들러를 등록하는 방법은?
A4: 여러 `http.HandleFunc`이나 `http.Handle`를 호출하여 각각의 경로와 핸들러를 등록합니다. 예:

```go
http.HandleFunc("/", homeHandler)
http.HandleFunc("/about", aboutHandler)
http.HandleFunc("/static/", staticFileHandler)
```
접속한 경로에 맞는 핸들러가 실행됩니다.

---

Q5: 커스텀 핸들러를 구조체 형태로 만드는 방법은?
A5: `ServeHTTP(w http.ResponseWriter, r *http.Request)` 메서드를 가진 구조체를 생성하여 `http.Handler` 인터페이스를 구현합니다. 예:

```go
type myHandler struct {}

func (h *myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "This is a custom handler")
}

func main() {
handler := &myHandler{}
http.ListenAndServe(":8080", handler)
}
```

---

Q6: HTTP 서버를 멀티코어에서 효율적으로 동작하게 하려면?
A6: Go 런타임의 기본 HTTP 서버는 고루틴을 사용하여 다중 요청을 동시에 처리합니다. 별도의 작업 없이도 멀티코어에서 효율적으로 동작하지만, CPU 코어 수를 늘리고 싶으면 프로그램 시작 시 `runtime.GOMAXPROCS` 값을 조절할 수 있습니다. 보통은 기본 값으로 충분합니다.

---
Q7: HTTP 요청에서 쿼리 파라미터를 읽는 방법은?
A7: `*http.Request` 객체의 `URL.Query()`를 사용합니다. 예:

```go
func handler(w http.ResponseWriter, r *http.Request) {
values := r.URL.Query()
name := values.Get("name")
fmt.Fprintf(w, "Hello %s!", name)
}
```

---

Q8: POST 요청의 본문 데이터를 읽으려면?
A8: `r.Body`를 읽으면 됩니다. 예:

```go
func handler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Only POST allowed", http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Failed to read body", http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "Received: %s", string(body))
}
```

---

Q9: 서버에 HTTPS를 적용하려면 어떻게 해야 하나요?
A9: `http.ListenAndServeTLS` 함수를 사용합니다. 인증서 파일 경로와 키 파일 경로를 지정해야 합니다. 예:

```go
http.ListenAndServeTLS(":443", "cert.pem", "key.pem", nil)
```

---

Q10: 정적 파일을 제공하는 가장 간단한 방법은?
A10: `http.FileServer`를 사용합니다. 예:

```go
fs := http.FileServer(http.Dir("./static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
```
`./static` 디렉토리의 파일들을 `/static/` 경로로 제공할 수 있습니다.

---

Q11: 커스텀 미들웨어를 만드는 방법은?
A11: 핸들러를 감싸는 형태로 `http.Handler` 또는 `http.HandlerFunc`를 반환하는 함수를 만듭니다. 예:

```go
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("Request: %s %s", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
})
}

func main() {
handler := http.HandlerFunc(yourHandler)
http.ListenAndServe(":8080", loggingMiddleware(handler))
}
```

---

요약하자면, Go에서 HTTP 서버는 `net/http` 패키지를 중심으로 간편하게 만들 수 있으며, 기본적인 핸들러 등록부터 커스텀 미들웨어, HTTPS 적용, 정적 파일 제공까지 유연하게 확장 가능합니다.
Go 언어는 간결하고 효율적인 HTTP 서버를 쉽게 만들 수 있는 강력한 기능을 제공합니다.

Go의 표준 라이브러리에는 HTTP 서버를 구축하는 데 필요한 패키지가 포함되어 있어, 복잡한 설정 없이도 빠르게 서버를 시작할 수 있습니다.

아래에서는 Go에서 HTTP 서버를 만드는 방법에 대해 단계별로 설명하겠습니다.

1. Go 설치 먼저, Go 언어가 설치되어 있어야 합니다.

Go의 공식 웹사이트(https://golang.org/dl/)에서 설치 파일을 다운로드하고 설치합니다.

설치가 완료되면, 터미널에서 `go version` 명령어를 입력하여 설치가 제대로 되었는지 확인합니다.



2. 기본 HTTP 서버 만들기 Go에서 HTTP 서버를 만드는 기본적인 방법은 `net/http` 패키지를 사용하는 것입니다.

아래는 간단한 HTTP 서버의 예제입니다.

```go package main import ( "fmt" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, World!") } func main() { http.HandleFunc("/", handler) // 루트 경로에 대한 핸들러 등록 fmt.Println("서버가 http://localhost:8080에서 실행 중입니다.

") http.ListenAndServe(":8080", nil) // 서버 시작 } ``` 위 코드는 기본적인 HTTP 서버를 설정합니다.

`http.HandleFunc`를 사용하여 루트 경로("/")에 대한 요청을 처리하는 `handler` 함수를 등록합니다.

`http.ListenAndServe`는 지정된 포트(여기서는 8080)에서 서버를 시작합니다.



3. 서버 실행 위 코드를 `main.go`라는 파일로 저장한 후, 터미널에서 다음 명령어를 실행하여 서버를 시작합니다.

```bash go run main.go ``` 서버가 실행되면 웹 브라우저에서 `http://localhost:8080`에 접속하여 "Hello, World!" 메시지를 확인할 수 있습니다.



4. 다양한 핸들러 추가하기 여러 경로에 대해 다양한 핸들러를 추가할 수 있습니다.

예를 들어, 다음과 같이 여러 경로를 처리할 수 있습니다.

```go package main import ( "fmt" "net/http" ) func helloHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, World!") } func goodbyeHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Goodbye, World!") } func main() { http.HandleFunc("/hello", helloHandler) http.HandleFunc("/goodbye", goodbyeHandler) fmt.Println("서버가 http://localhost:8080에서 실행 중입니다.

") http.ListenAndServe(":8080", nil) } ``` 이제 `/hello` 경로에 접속하면 "Hello, World!" 메시지를, `/goodbye` 경로에 접속하면 "Goodbye, World!" 메시지를 확인할 수 있습니다.



5. 정적 파일 제공하기 Go는 정적 파일을 제공하는 것도 매우 간단합니다.

`http.FileServer`를 사용하여 특정 디렉토리의 파일을 제공할 수 있습니다.

```go package main import ( "net/http" ) func main() { fs := http.FileServer(http.Dir("./static")) // static 디렉토리의 파일 제공 http.Handle("/static/", http.StripPrefix("/static/", fs)) http.ListenAndServe(":8080", nil) } ``` 위 코드는 `./static` 디렉토리의 파일을 `/static/` 경로를 통해 제공하는 서버를 설정합니다.



6. 미들웨어 사용하기 Go에서는 미들웨어를 사용하여 요청을 가로채고 처리할 수 있습니다.

예를 들어, 로깅 미들웨어를 추가할 수 있습니다.

```go package main import ( "fmt" "log" "net/http" ) func loggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Printf("요청: %s %s", r.Method, r.URL.Path) next.ServeHTTP(w, r) }) } func main() { http.Handle("/", loggingMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, World!") }))) http.ListenAndServe(":8080", nil) } ``` 위 코드는 모든 요청에 대해 로그를 출력하는 미들웨어를 추가합니다.



7. JSON 응답 보내기 Go에서 JSON 응답을 보내는 것도 간단합니다.

`encoding/json` 패키지를 사용하여 구조체를 JSON으로 변환할 수 있습니다.

```go package main import ( "encoding/json" "net/http" ) type Message struct { Text string `json:"text"` } func messageHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(Message{Text: "Hello, World!"}) } func main() { http.HandleFunc("/json", messageHandler) http.ListenAndServe(":8080", nil) } ``` 위 코드는 `/json` 경로에 접속할 때 JSON 형식의 응답을 반환합니다.



8. Go 언어를 사용하여 HTTP 서버를 만드는 것은 매우 간단하고 직관적입니다.

기본적인 서버 설정부터 시작하여, 다양한 핸들러, 정적 파일 제공, 미들웨어, JSON 응답 등 다양한 기능을 추가할 수 있습니다.

이러한 기능들을 조합하여 복잡한 웹 애플리케이션을 구축할 수 있습니다.

Go의 강력한 성능과 간결한 문법 덕분에 많은 개발자들이 Go를 선택하고 있습니다.

작성자: 박다온 [비회원] | 작성일자: 1년 전 2024-09-19 01:50:28
조회수: 173 | 댓글: 0 | 좋아요: 0 | 싫어요: 0
내용이 부정확하다면 싫어요를 클릭해주세요.