요약 - REST API 모델
Coddy GO 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 107개 중 78번째.
챌린지
쉬움블로그 플랫폼을 위한 REST API 모델 시스템을 만들어 봅시다! JSON으로 직렬화되고 읽기 쉬운 문자열 표현을 제공하는 잘 구조화된 타입을 만들 것입니다. 실제 API 응답을 만들 때 정확히 필요한 방식입니다.
코드를 두 파일로 구성합니다:
models.go: 적절한 JSON 태그와 문자열 표현을 사용하여 API 데이터 모델을 Define합니다.Authorstruct를 만들고ID(int),Name(string),Email(string) Fields를 추가합니다. 이를 JSON 키"id","name","email"에 매핑합니다.String()을 Implement하여[Name] <[Email]>형식을 Return하도록 합니다.Poststruct를 만들고ID(int),Title(string),Content(string),Author(중첩된 Author struct),Published(bool)를 추가합니다. 이를"id","title","content","author","published"에 매핑합니다.Content필드는 빈 콘텐츠가 JSON에 나타나지 않도록omitempty를 사용해야 합니다.String()을 Implement하여"[Title]" by [Author's String representation]을 Return하도록 합니다.APIResponsestruct를 만들고Success(bool),Message(string),Data(Post)를 추가합니다."success","message","data"에 매핑합니다.Message필드는omitempty를 사용해야 합니다.main.go: API 응답을 만들고 JSON 출력과 문자열 표현을 모두 보여 줍니다.작업 유형(
json또는display)을 Read한 다음, 게시물 세부 정보인 게시물 ID, 제목, 콘텐츠, 작성자 ID, 작성자 이름, 작성자 이메일, 게시 상태(true또는false)를 Read합니다.json의 경우:Success: true인 APIResponse를 만들고 Post를 data로 설정합니다(Message는 비워 둡니다). JSON으로 Convert한 후 Print합니다.display의 경우: Post를 만들고 해당 String method를 사용하여 Print한 다음, 새 줄에 Author를 별도로 Print합니다.
다음 입력이 제공됩니다:
- 1번째 줄: 작업 유형(
json또는display) - 2번째 줄: Post ID
- 3번째 줄: 제목
- 4번째 줄: 콘텐츠(비어 있을 수 있음)
- 5번째 줄: Author ID
- 6번째 줄: Author 이름
- 7번째 줄: Author 이메일
- 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}}빈 콘텐츠 필드가 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 모델직접 연습해 보세요: 온라인 Go 컴파일러