요약 - REST API 모델
Coddy GO 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨 — 107개 중 78번째.
챌린지
쉬움블로그 플랫폼을 위한 REST API 모델 시스템을 구축해 봅시다! JSON으로 직렬화되고 읽기 쉬운 문자열 표현을 제공하는 잘 구조화된 타입을 만들게 됩니다. 이는 실제 API 응답을 구축할 때 정확히 필요한 작업입니다.
코드는 두 개의 파일로 구성됩니다:
models.go: 적절한 JSON 태그와 문자열 표현을 갖춘 API 데이터 모델을 정의합니다.ID(int),Name(string),Email(string) 필드를 가진Author구조체를 생성하세요. 이 필드들을 JSON 키"id","name","email"에 매핑하세요.[Name] <[Email]>형식을 반환하는String()메서드를 구현하세요.ID(int),Title(string),Content(string),Author(중첩된 Author 구조체),Published(bool) 필드를 가진Post구조체를 생성하세요. 이 필드들을"id","title","content","author","published"에 매핑하세요.Content필드는omitempty를 사용하여 빈 내용이 JSON에 나타나지 않도록 해야 합니다."[Title]" by [Author's String representation]을 반환하는String()메서드를 구현하세요.Success(bool),Message(string),Data(Post) 필드를 가진APIResponse구조체를 생성하세요."success","message","data"에 매핑하세요.Message필드는omitempty를 사용해야 합니다.main.go: API 응답을 구축하고 JSON 출력과 문자열 표현을 모두 보여줍니다.작업 유형(
json또는display)을 읽은 다음, 포스트 상세 정보인 포스트 ID, 제목, 내용, 작성자 ID, 작성자 이름, 작성자 이메일, 게시 상태(true또는false)를 읽습니다.json의 경우:Success: true와 Post를 데이터로 가지는 APIResponse를 생성하세요 (Message는 비워둡니다). 이를 JSON으로 변환하여 출력하세요.display의 경우: Post를 생성하고 해당 String 메서드를 사용하여 출력한 다음, 작성자 정보를 새 줄에 별도로 출력하세요.
다음 입력이 제공됩니다:
- Line 1: 작업 유형 (
json또는display) - Line 2: 포스트 ID
- Line 3: 제목
- Line 4: 내용 (비어 있을 수 있음)
- Line 5: 작성자 ID
- Line 6: 작성자 이름
- Line 7: 작성자 이메일
- Line 8: 게시 상태 (
true또는false)
예를 들어, 다음과 같이 입력되면:
json
1
Getting Started with Go
Learn the basics of Go programming
101
Jane Smith
jane@example.com
true출력은 다음과 같아야 합니다:
{"success":true,"data":{"id":1,"title":"Getting Started with Go","content":"Learn the basics of Go programming","author":{"id":101,"name":"Jane Smith","email":"jane@example.com"},"published":true}}그리고 다음과 같이 입력되면:
json
2
Draft Post
102
John Doe
john@example.com
false출력은 다음과 같아야 합니다:
{"success":true,"data":{"id":2,"title":"Draft Post","author":{"id":102,"name":"John Doe","email":"john@example.com"},"published":false}}빈 content 필드가 JSON 출력에서 어떻게 생략되는지 확인하세요.
그리고 다음과 같이 입력되면:
display
3
Advanced Interfaces
Deep dive into Go interfaces
103
Alice Chen
alice@example.com
true출력은 다음과 같아야 합니다:
"Advanced Interfaces" by Alice Chen <alice@example.com>
Alice Chen <alice@example.com>직접 해보기
package main
import (
"bufio"
"encoding/json"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
// 작업 유형 읽기
operation, _ := reader.ReadString('\n')
operation = strings.TrimSpace(operation)
// 게시글 ID 읽기
postIDStr, _ := reader.ReadString('\n')
postID, _ := strconv.Atoi(strings.TrimSpace(postIDStr))
// 제목 읽기
title, _ := reader.ReadString('\n')
title = strings.TrimSpace(title)
// 내용 읽기
content, _ := reader.ReadString('\n')
content = strings.TrimSpace(content)
// 작성자 ID 읽기
authorIDStr, _ := reader.ReadString('\n')
authorID, _ := strconv.Atoi(strings.TrimSpace(authorIDStr))
// 작성자 이름 읽기
authorName, _ := reader.ReadString('\n')
authorName = strings.TrimSpace(authorName)
// 작성자 이메일 읽기
authorEmail, _ := reader.ReadString('\n')
authorEmail = strings.TrimSpace(authorEmail)
// 게시 상태 읽기
publishedStr, _ := reader.ReadString('\n')
published := strings.TrimSpace(publishedStr) == "true"
// TODO: 읽어온 값들로 `Author` 구조체 생성
// TODO: 읽어온 값들과 `Author`를 사용하여 `Post` 구조체 생성
// TODO: 작업 유형 처리
// operation이 "json"인 경우:
// - Success: true와 Post를 Data로 가지는 APIResponse 생성
// - json.Marshal을 사용하여 JSON으로 변환
// - JSON 문자열 출력
// operation이 "display"인 경우:
// - String 메서드를 사용하여 Post 출력
// - 새 줄에 Author 출력
// 변수 사용을 위한 플레이스홀더 (구현 시 제거)
_ = postID
_ = title
_ = content
_ = authorID
_ = authorName
_ = authorEmail
_ = published
_ = operation
_ = json.Marshal
fmt.Println("TODO: Implement the solution")
}
객체 지향 프로그래밍의 모든 레슨
8에러 처리와 OOP
error 인터페이스사용자 정의 에러 타입에러 래핑 (fmt.Errorf)센티넬 에러errors.Is()와 errors.As()Panic, Defer, Recover요약 - 파일 파서11표준 라이브러리 & OOP
io.Reader & io.Writersort.Interfacefmt.Stringer 인터페이스encoding/json과 구조체http.Handler 인터페이스요약 - REST API 모델