Recommanded Free YOUTUBE Lecture: <% selectedImage[1] %>

예제로 살펴보는 Go : Simple Web Server

Go언어는 "net/http"라는 웹 애플리케이션 개발을 지원하는 패키지를 제공한다. 매우 사용하기 쉽고, 강력하기 때문에 "다른 프레임워크 사용 할 필요 없다. net/http 만 써도 충분하다"라는 평가를 받기도 한다. 풀 프레임워크 목적으로 사용하기에는 부족하지만 REST API 서버 개발 목적이라면 이걸로 충분하다.

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/hello", hello)
    http.HandleFunc("/headers", headers)
    http.ListenAndServe(":8000", nil)
}

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

func headers(w http.ResponseWriter, r *http.Request) {
    for key, value := range r.Header {
        for _, h := range value {
            fmt.Fprintf(w, "%v: %v\n", key, h)
        }
    }
}
http.HandleFunc 패키지를 이용해서, URL PATH를 처리하기 위한 핸들러 함수를 등록 할 수 있다.

핸들러 함수는 http.ResponseWriter 와 http.Request 를 인자로 받는다. http.Request는 클라이언트의 HTTP 요청 데이터와 이를 처리하기 위한 메서드들을 가지고 있다.

테스트
# curl localhost:8000/headers -H "x-app-name: joinc,name" -H "Accept: application/json, plain/text" -i
HTTP/1.1 200 OK
Date: Wed, 13 May 2020 09:40:45 GMT
Content-Length: 84
Content-Type: text/plain; charset=utf-8

X-App-Name: joinc,name
Accept: application/json, plain/text
User-Agent: curl/7.64.0

# curl 'localhost:8000/hello?yundream' -i
HTTP/1.1 200 OK
Date: Wed, 13 May 2020 09:41:46 GMT
Content-Length: 6
Content-Type: text/plain; charset=utf-8

Hello %