Menu
CoddyTech

요약 - REST API 모델

Coddy GO 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 107개 중 78번째.

challenge icon

챌린지

쉬움

블로그 플랫폼을 위한 REST API 모델 시스템을 만들어 봅시다! JSON으로 직렬화되고 읽기 쉬운 문자열 표현을 제공하는 잘 구성된 타입을 만들 거예요. 실제 API 응답을 만들 때 필요한 바로 그런 것들이죠.

코드를 두 파일로 나누어 구성할 거예요.

  • models.go: 적절한 JSON 태그와 문자열 표현을 사용해 API 데이터 모델을 정의합니다.

    Author 구조체를 만들고 ID(int), Name(string), Email(string) 필드를 추가합니다. 이 필드들을 JSON 키 "id", "name", "email"에 매핑합니다. String()을 구현해 [Name] <[Email]> 형식으로 반환합니다.

    Post 구조체를 만들고 ID(int), Title(string), Content(string), Author(중첩된 Author 구조체), Published(bool) 필드를 추가합니다. 이 필드들을 "id", "title", "content", "author", "published"에 매핑합니다. Content 필드에는 omitempty를 사용하여 내용이 비어 있으면 JSON에 나타나지 않도록 합니다. String()을 구현해 "[Title]" by [Author's String representation]을 반환합니다.

    APIResponse 구조체를 만들고 Success(bool), Message(string), Data(Post) 필드를 추가합니다. "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 메서드를 사용해 출력하고, 이어서 다음 줄에 Author를 별도로 출력합니다.

다음 입력이 제공됩니다.

  • 1행: 작업 유형(json 또는 display)
  • 2행: 게시물 ID
  • 3행: 제목
  • 4행: 내용(비어 있을 수 있음)
  • 5행: 작성자 ID
  • 6행: 작성자 이름
  • 7행: 작성자 이메일
  • 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"이면:
	//   - Post의 String 메서드를 사용해 Post를 출력합니다
	//   - 새 줄에 Author를 출력합니다

	// 변수를 사용하기 위한 임시 코드(구현할 때 제거)
	_ = postID
	_ = title
	_ = content
	_ = authorID
	_ = authorName
	_ = authorEmail
	_ = published
	_ = operation
	_ = json.Marshal
	fmt.Println("TODO: Implement the solution")
}

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 Go 컴파일러