본문 바로가기
Programming/Golang

Go언어 - Gin Framework(4강 개별 Article 화면 구성)

by Wilkyway 2020. 12. 15.
반응형
개별 Article 화면 구성

현재까지 구성한 앱에서는 Article을 클릭했을 때 링크가 작동하지 않았습니다. 이번에는 각 Article에 대한 핸들러와 템플릿을 추가하도록 하겠습니다.

1. Route 설정

router.GET("/article/view/:article_id", getArticle)

main함수의 Route 설정 부분에 위구문을 추가합니다. 위 라우터는 패턴과 맞는 요청에 대해 경로를 일치시키고, 경로 마지막부분을 route 파라미터인 article_id에 저장합니다. 이 라우터에서는 handler함수로 getArticle을 정의합니다.

 

main.go 전체 코드 모습

package main

import (
	//"net/http"

	"github.com/gin-gonic/gin"
)

var router *gin.Engine

func main() {
	router := gin.Default()

	router.LoadHTMLGlob("templates/*")

	router.GET("/", showIndexPage)
	router.GET("/article/view/:article_id", getArticle)

	router.Run()

}

 

2. View Templates 만들기

개별 Article Contents를 표현할 새 템플릿 templates/article.html 을 생성하겠습니다.

<!--article.html-->

<!--Embed the header.html template at this location-->
{{ template "header.html" .}}

<!--Display the title of the article-->
<h1>{{.payload.Title}}</h1>

<!--Display the content of the article-->
<p>{{.payload.Content}}</p>

<!--Embed the footer.html template at this location-->
{{ template "footer.html" .}}

유닛 테스트....가 필요한데 Pass...

3. Route Handler 생성

Article 추출

models.article.go파일에  getArticleByID() 함수 정의하여 article을 가져오는 기능을 추가합니다.

package main

import "errors"

type article struct {
	ID      int    `json:"id"`
	Title   string `json:"title"`
	Content string `json:"content"`
}

// For this demo, we're storing the article list in memory
// In a real application, this list will most likely be fetched
// from a database or from static files
var articleList = []article{
	article{ID: 1, Title: "Article 1", Content: "Article 1 body"},
	article{ID: 2, Title: "Article 2", Content: "Article 2 body"},
}

// Return a list of all the articles
func getAllArticles() []article {
	return articleList
}

func getArticleByID(id int) (*article, error) {
	for _, a := range articleList {
		if a.ID == id {
			return &a, nil
		}
	}
	return nil, errors.New("Article not found")
}

getArticleByID 함수는 Article List를 반복하다가 ID가 일치할 경우 해당 Article을 반환합니다. 일치하는 기사가 없으면 오류를 반환합니다.

 

handlers.article.go파일 수정

Article을 article.html 템플릿에 전달하여 렌더링하도록 getArticle 함수를 추가합니다.

// handlers.article.go

package main

import (
  "net/http"
  "strconv"

  "github.com/gin-gonic/gin"
)

func showIndexPage(c *gin.Context) {
  articles := getAllArticles()

  // Call the HTML method of the Context to render a template
  c.HTML(
    // Set the HTTP status to 200 (OK)
    http.StatusOK,
    // Use the index.html template
    "index.html",
    // Pass the data that the page uses
    gin.H{
      "title":   "Home Page",
      "payload": articles,
    },
  )

}

func getArticle(c *gin.Context) {
  // Check if the article ID is valid
  if articleID, err := strconv.Atoi(c.Param("article_id")); err == nil {
    // Check if the article exists
    if article, err := getArticleByID(articleID); err == nil {
      // Call the HTML method of the Context to render a template
      c.HTML(
        // Set the HTTP status to 200 (OK)
        http.StatusOK,
        // Use the index.html template
        "article.html",
        // Pass the data that the page uses
        gin.H{
          "title":   article.Title,
          "payload": article,
        },
      )

    } else {
      // If the article is not found, abort with an error
      c.AbortWithError(http.StatusNotFound, err)
    }

  } else {
    // If an invalid article ID is specified in the URL, abort with an error
    c.AbortWithStatus(http.StatusNotFound)
  }
}

 

<결과>

 

 

 

<파일구성>

 

 

 

 
반응형

댓글