Menu
Coddy logo textTech

まとめ:REST API モデル

CoddyのGOジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 78/107。

challenge icon

チャレンジ

簡単

ブログプラットフォーム向けのREST APIモデルシステムを構築しましょう!JSONにシリアライズでき、読みやすい文字列表現を提供する、適切に構造化された型を作成します。これは、実際のAPIレスポンスを構築するときに必要となるものです。

コードを2つのファイルに整理します。

  • models.go:適切なJSONタグと文字列表現を持つAPIデータモデルをDefineします。

    Author構造体を作成し、ID(int)、Name(string)、Email(string)Fieldsを持たせます。これらをJSONキー"id""name""email"に対応付けます。String()をImplementし、形式[Name] <[Email]>をReturnするようにします。

    Post構造体を作成し、ID(int)、Title(string)、Content(string)、Author(ネストされたAuthor構造体)、Published(bool)Fieldsを持たせます。これらを"id""title""content""author""published"に対応付けます。空のContentがJSONに表示されないよう、Contentフィールドではomitemptyを使用します。String()をImplementし、"[Title]" by [Author's String representation]をReturnするようにします。

    APIResponse構造体を作成し、Success(bool)、Message(string)、Data(Post)を持たせます。"success""message""data"に対応付けます。Messageフィールドではomitemptyを使用します。

  • main.go:APIレスポンスを作成し、JSON出力と文字列表現の両方を示します。

    操作タイプ(jsonまたはdisplay)をReadし、続いてpostの詳細情報(post ID、title、content、author ID、author name、author email、published status(trueまたはfalse))をReadします。

    jsonの場合:Success: trueとPostをdataとしてAPIResponseをCreateします(Messageは空のままにします)。JSONにConvertしてPrintします。

    displayの場合:PostをCreateし、そのString methodを使用してPrintします。その後、Authorを別の行にPrintします。

次の入力が提供されます。

  • 1行目:操作タイプ(jsonまたはdisplay
  • 2行目:Post ID
  • 3行目:Title
  • 4行目:Content(空の場合があります)
  • 5行目:Author ID
  • 6行目:Author name
  • 7行目:Author email
  • 8行目:Published status(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: 操作タイプを処理する
	// 操作が "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")
}

オブジェクト指向プログラミングのすべてのレッスン

自分で練習してみよう: Goオンラインコンパイラ