개별 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)
}
}
댓글0