Cheat Sheet - Linux: /kr/linux/ - CLI: /kr/linux/cli/ - locate vs type vs which vs whereis: /kr/linux/cli/locate-vs-type-vs-which-vs-whereis/ - make: /kr/linux/cli/make/ - awk: /kr/linux/cli/awk/ - find: /kr/linux/cli/find/ - grep: /kr/linux/cli/grep/ - pgrep: /kr/linux/cli/pgrep/ - ps: /kr/linux/cli/ps/ - pstree: /kr/linux/cli/pstree/ - trap: /kr/linux/cli/trap/ - xargs: /kr/linux/cli/xargs/ - Shell: /kr/linux/shell/ - BASH_SOURCE: /kr/linux/shell/bash-source/ - Redirection: /kr/linux/shell/redirection/ - Special Variables: /kr/linux/shell/special-variables/ - Interactive Shell과 Login Shell의 정의: /kr/linux/shell/interactive-login/ - Scripting Tips: /kr/linux/shell/script-tips/ - set -o vi: /kr/linux/shell/bash-vi-mode/ - Shell 실행 순서: /kr/linux/shell/process-order/ - Double Quote Expansion: /kr/linux/shell/shell-expansion/ - System Programming: /kr/linux/system-programming/ - File I/O: /kr/linux/system-programming/file-io/ - Process: /kr/linux/system-programming/process/ - Shared Libraries: /kr/linux/system-programming/shared-libraries/ - Kernel: /kr/linux/kernel/ - Go: /kr/programming/go/ - Concurrency: /kr/programming/go/concurrency/ - CSP (Communicating Sequential Processes) and Channels: /kr/programming/go/concurrency/csp/ - Channel: /kr/programming/go/concurrency/channel/ - Select: /kr/programming/go/concurrency/select/ - sync: /kr/programming/go/concurrency/sync/ - Concurrency Patterns: /kr/programming/go/concurrency/patterns/ - Goroutines and the Go Runtime: /kr/programming/go/concurrency/runtime/ - 표준 라이브러리: /kr/programming/go/std/ - os: /kr/programming/go/std/os/ - context: /kr/programming/go/std/context/ - io: /kr/programming/go/std/io/ - json: /kr/programming/go/std/json/ - net/http: /kr/programming/go/std/net-http/ - slog: /kr/programming/go/std/slog/ - testing: /kr/programming/go/std/testing/ - time: /kr/programming/go/std/time/ - Ellipsis (...): /kr/programming/go/ellipsis/ - error: /kr/programming/go/error/ - Function: /kr/programming/go/function/ - Go Tool: /kr/programming/go/tool/ - Interface: /kr/programming/go/interface/ - Map: /kr/programming/go/map/ - Package and Module: /kr/programming/go/package-module/ - Pointer: /kr/programming/go/pointer/ - Slice: /kr/programming/go/slice/ - String: /kr/programming/go/string/ - Switch: /kr/programming/go/switch/ - Comparison: /kr/programming/go/comparison/ - defaultdict: /kr/programming/python/collections/defaultdict/ - heapq: /kr/programming/python/collections/heapq/ - @cache: /kr/programming/python/cache/ - abc: /kr/programming/python/abc/ - bisect: /kr/programming/python/bisect/ - Type Hints: /kr/programming/python/type-hints/ - Passing Mechanism: /kr/programming/python/passing-mechanism/ - uv: /kr/programming/python/uv/ - *args and **kwargs: /kr/programming/python/args-kwargs/ - re: /kr/programming/python/re/ - C: /kr/programming/c/ - 포인터와 배열: /kr/programming/c/pointer/ - Syntax Basics: /kr/programming/c/syntax-basics/ - static: /kr/programming/c/static/ - Bit Manipulation: /kr/programming/c/bit-manipulation/ - C vs C++: /kr/programming/c/c-vs-cpp/ - stdatomic: /kr/programming/c/stdatomic/ - C++: /kr/programming/cpp/ - RAII (Resource Acquisition Is Initialization): /kr/programming/cpp/raii/ - Copy Elision & Move Semantics: /kr/programming/cpp/copy-elision-and-move-semantics/ - Most Vexing Parse & In-Class Initializer: /kr/programming/cpp/most-vexing-parse/ - C++ Keywords Reference: /kr/programming/cpp/keywords/ - C++ Primer: /kr/programming/cpp/primer/ - Variables and Basic Types: /kr/programming/cpp/primer/variables-and-basic-types/ - Expressions: /kr/programming/cpp/primer/expressions/ - Type Conversions and Casts: /kr/programming/cpp/primer/type-conversions-and-casts/ - Statements: /kr/programming/cpp/primer/statements/ - Functions: /kr/programming/cpp/primer/functions/ - Classes: /kr/programming/cpp/primer/classes/ - The IO Library: /kr/programming/cpp/primer/io-library/ - STL: /kr/programming/cpp/primer/stl/ - Lambda Expressions: /kr/programming/cpp/primer/lambda/ - Smart Pointers: /kr/programming/cpp/primer/smart-pointers/ - Copy Control: /kr/programming/cpp/primer/copy-control/ - Overloaded Operations and Conversions: /kr/programming/cpp/primer/operator-overloading/ - Object-Oriented Programming (OOP): /kr/programming/cpp/primer/oop/ - Templates and Generic Programming: /kr/programming/cpp/primer/templates/ - Namespaces: /kr/programming/cpp/primer/namespaces/ - Pointers to Class Member: /kr/programming/cpp/primer/pointers-to-class-member/ - Advanced: /kr/programming/cpp/advanced/ - Error Handling: /kr/programming/cpp/advanced/error-handling/ - Concurrency & Threading: /kr/programming/cpp/advanced/concurrency/ - Unit Testing: /kr/programming/cpp/advanced/unit-testing/ - 언어 별 비교: /kr/programming/comparison/ - Kubernetes: /kr/cloud-devops/kubernetes/ - Fleet: /kr/cloud-devops/kubernetes/gke/fleet/ - Kustomize vs Helm: /kr/cloud-devops/kubernetes/kustomize-vs-helm/ - API Extension: /kr/cloud-devops/kubernetes/api-extension/ - Concept: /kr/cloud-devops/kubernetes/kueue/concept/ - DRA: /kr/cloud-devops/kubernetes/dra/ - Secret Manager: /kr/cloud-devops/terraform/google-secret-manager/ - Knowledge: /kr/network/knowledge/ - PDU: /kr/network/knowledge/osi-model/ - curl: /kr/network/cli/curl/ - Concurrency Concepts: /kr/cs/concurrency-and-parallelism/concepts/ - Concurrency vs Parallelism: /kr/cs/concurrency-and-parallelism/concurrency-vs-parallelism/ - Mutex vs Atomic: /kr/cs/concurrency-and-parallelism/mutex-vs-atomic/ - Regular Expression: /kr/cs/regular-expression/ - Multiplexer vs Dispatcher: /kr/cs/multiplexer-vs-dispatcher/ - Driver and Runtime: /kr/ai-ml/gpu/driver-and-runtime/ - Serving: /kr/ai-ml/serving/ - Dotfiles: /kr/dotfiles/ - Git: /kr/dotfiles/git/ - Cheat Sheet: /kr/dotfiles/git/cheat-sheet/ - revisions: /kr/dotfiles/git/revisions/ - Submodule vs Worktree: /kr/dotfiles/git/submodule-vs-worktree/ - checkout, reset -> switch, restore: /kr/dotfiles/git/checkout-switch-restore-reset/ - rebase: /kr/dotfiles/git/rebase/ - Branching and Merging: /kr/dotfiles/git/branching-merging/ - Vim: /kr/dotfiles/vim/ - Plugin: /kr/dotfiles/vim/plugin/ - auto-pairs: /kr/dotfiles/vim/plugin/auto-pairs/ - vim-commentary: /kr/dotfiles/vim/plugin/vim-commentary/ - vim-easymotion: /kr/dotfiles/vim/plugin/vim-easymotion/ - vim-surround: /kr/dotfiles/vim/plugin/vim-surround/ - Marks: /kr/dotfiles/vim/tips/marks/ - vimrc: /kr/dotfiles/vim/vimrc/ - lf: /kr/dotfiles/lf/ # net/http ## Client 애플리케이션에서 다른 HTTP 서비스로 요청을 보낼 때는 `NewRequestWithContext` 함수를 사용하여 컨텍스트 취소 및 마감 기한이 준수되도록 한다. ```go func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error) ``` ```go client := &http.Client{ Timeout: 30 * time.Second, } req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "https://jsonplaceholder.typicode.com/todos/1", nil) if err != nil { panic(err) } req.Header.Add("X-My-Client", "Learning Go") res, err := client.Do(req) if err != nil { panic(err) } defer res.Body.Close() if res.StatusCode != http.StatusOK { panic(fmt.Sprintf("unexpected status: got %v", res.Status)) } fmt.Println(res.Header.Get("Content-Type")) var data any err = json.NewDecoder(res.Body).Decode(&data) ``` {{% hint warning %}} **주의:** `http.Get()` 등 패키지 레벨 함수는 `http.DefaultClient`를 사용한다. 이는 timeout 설정이 되어 있지 않으므로 직접 `http.Client`를 생성하여 사용하는 것을 권장한다. {{% /hint %}} ## Server ### `http.Handler` 및 `http.HandlerFunc` - **`http.Handler` 인터페이스** ```go type Handler interface { ServeHTTP(ResponseWriter, *Request) } ``` - **`http.HandlerFunc` 어댑터** ```go type HandlerFunc func(ResponseWriter, *Request) ``` - `HandlerFunc` 타입은 일반 함수를 HTTP 핸들러로 사용할 수 있게 해주는 어댑터다. 적절한 signature를 가진 함수 `f`가 있다면, `HandlerFunc(f)`는 `f`를 호출하는 `Handler`가 된다. ### `http.ResponseWriter` ```go type ResponseWriter interface { Header() http.Header Write([]byte) (int, error) WriteHeader(statusCode int) } ``` - 메서드 호출 순서가 중요하다: `Header` -> `WriteHeader` -> `Write` #### `http.ResponseController` - `http.ResponseWriter`가 인터페이스이므로, 하위 호환성을 유지하며 새로운 메서드를 추가하기 위해 구체 타입(concrete type)인 `http.ResponseController`를 통한다. - 래핑된 `http.ResponseWriter`가 특정 메서드를 지원하지 않으면 타입 단언(type assertion)을 통해 `http.ErrNotSupported`를 반환한다. - `func NewResponseController(rw ResponseWriter) *ResponseController`: `http.ResponseWriter`로부터 `ResponseController`를 생성한다. - `func (c *ResponseController) Flush() error` - `func (c *ResponseController) Hijack() (net.Conn, *bufio.ReadWriter, error)` ### `http.Request` - `func (r *Request) Context() context.Context`: 요청의 컨텍스트를 반환한다. 컨텍스트를 변경하려면 `WithContext`를 사용한다. - `func (r *Request) WithContext(ctx context.Context) *Request`: 컨텍스트가 `ctx`로 변경된 요청의 얕은 복사본(shallow copy)을 반환한다. - `func (r *Request) ParseForm() error`: URL의 쿼리를 파싱하여 `r.Form`을 업데이트한다. POST, PUT, PATCH 요청의 경우 바디(body)를 폼으로 읽어 `r.PostForm`과 `r.Form`을 업데이트한다. - `func (r *Request) FormValue(key string) string`: 쿼리에서 해당 키의 첫 번째 값을 반환한다. 필요한 경우 내부적으로 `ParseForm`을 호출한다. ### `http.Server` ```go s := http.Server{ Addr: ":8080", ReadTimeout: 30 * time.Second, WriteTimeout: 90 * time.Second, IdleTimeout: 120 * time.Second, Handler: HelloHandler{}, } err := s.ListenAndServe() ``` - **`http.ListenAndServe()` (패키지 레벨 함수):** `Handler` 필드를 `DefaultServeMux`로 사용하는 `http.Server` 객체를 만들어준다. - **`s.ListenAndServe()` (메서드):** `http.Server`를 직접 설정할 경우, 사용자가 직접 지정한 핸들러를 사용한다. ### `http.ServeMux` - **요청 라우터 (Request Router):** `http.Server.Handler`를 특정 `http.Handler`로 고정하면 단 하나의 동작만 처리할 수 있다. 경로(path)별로 핸들러를 분산(dispatch)하는 라우팅을 위해 `http.ServeMux`를 사용한다. - `http.NewServeMux()`로 생성한다. - `http.Handler` 인터페이스를 만족하므로 `http.Server`의 `Handler` 필드에 할당할 수 있다. #### 메서드 - `func (mux *ServeMux) Handle(pattern string, handler Handler)` - `func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))` {{% hint warning %}} **주의:** `http.Handle`, `http.HandleFunc`, `http.ListenAndServe`, `http.ListenAndServeTLS` 등 패키지 레벨 함수는 간단한 테스트 외에는 사용을 지양한다. - 이 함수들은 `http.DefaultServeMux`라는 패키지 레벨의 `*http.ServeMux` 인스턴스를 사용한다. - `http.Server` 인스턴스가 함수 내부에서 생성되므로, 타임아웃과 같은 서버 속성을 직접 설정할 수 없다. {{% /hint %}} ### Middleware - **패턴:** `http.Handler`를 인자로 받아 `http.Handler`를 반환하는 함수다. 반환된 핸들러는 보통 원래의 핸들러를 호출하기 전이나 후에 특정 로직을 수행하는 클로저(closure)다. ```go func Middleware(handler http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { ctx := req.Context() // wrap the context with stuff req = req.WithContext(ctx) handler.ServeHTTP(rw, req) }) } ``` #### `ServeMux`와 함께 사용하기 ```go mux := http.NewServeMux() mux.Handle("/hello", Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello!\n")) }))) s := http.Server{ Addr: ":8080", Handler: mux, } s.ListenAndServe() ```