Go 언어의 웹 프레임워크 "Echo"①(Hello World의)
Go 언어로 웹 사이트 만들기: 목록
http://qiita.com/y_ussie/items/8fcc3077274449478bc9
Qiita 기고는 이번이 처음입니다.
Go의 웹 프레임워크를 사용해 Martini와 Gin을 조사해 보고 싶었지만, 에코는 새로운 프레임워크 개발도 활발한 것 같아 기본적인 사용법을 시도해 보기로 했다.
하고 싶은 일 
다음 요청을 처리합니다.
GET /
 
다음 템플릿으로 생성된 HTML을 반환합니다.
모든 페이지에 공통으로 적용되는 레이아웃 템플릿
templates/layout.html<html>
  <head>
    <title>Echo HTML Server Sample</title>
  </head>
  <body>
    <!-- Render the current template here -->
    {{template "content" .}}
  </body>
</html>
각 컨텐츠의 템플릿
templates/hello.html{{define "content"}}
<h2>Hello {{.}}!</h2>
{{end}}
GET /api/hello
 
다음 JSON으로 돌아갑니다.{"hello": "world"}
GET /public/css | js | img
 
정적 파일을 반환합니다.
그래서 나는 각양각색의 자료를 찾아보면서 썼다 
main.gopackage main
import (
    "html/template"
    "io"
    "net/http"
    "github.com/labstack/echo"
    "github.com/labstack/echo/middleware"
)
// レイアウト適用済のテンプレートを保存するmap
var templates map[string]*template.Template
// Template はHTMLテンプレートを利用するためのRenderer Interfaceです。
type Template struct {
}
// Render はHTMLテンプレートにデータを埋め込んだ結果をWriterに書き込みます。
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
    return templates[name].ExecuteTemplate(w, "layout.html", data)
}
func main() {
    // Echoのインスタンスを生成
    e := echo.New()
    // テンプレートを利用するためのRendererの設定
    t := &Template{}
    e.Renderer = t
    // ミドルウェアを設定
    e.Use(middleware.Logger())
    e.Use(middleware.Recover())
    // 静的ファイルのパスを設定
    e.Static("/public/css/", "./public/css")
    e.Static("/public/js/", "./public/js/")
    e.Static("/public/img/", "./public/img/")
    // 各ルーティングに対するハンドラを設定
    e.GET("/", HandleIndexGet)
    e.GET("/api/hello", HandleAPIHelloGet)
    // サーバーを開始
    e.Logger.Fatal(e.Start(":3000"))
}
// 初期化を行います。
func init() {
    loadTemplates()
}
// 各HTMLテンプレートに共通レイアウトを適用した結果を保存します(初期化時に実行)。
func loadTemplates() {
    var baseTemplate = "templates/layout.html"
    templates = make(map[string]*template.Template)
    templates["index"] = template.Must(
        template.ParseFiles(baseTemplate, "templates/hello.html"))
}
// HandleIndexGet は Index のGet時のHTMLデータ生成処理を行います。
func HandleIndexGet(c echo.Context) error {
    return c.Render(http.StatusOK, "index", "World")
}
// HandleAPIHelloGet は /api/hello のGet時のJSONデータ生成処理を行います。
func HandleAPIHelloGet(c echo.Context) error {
    return c.JSON(http.StatusOK, map[string]interface{}{"hello": "world"})
}
처음에는 에코의 가이드https://echo.labstack.com/guide를 보면서 쓰기 시작했지만, 공동 레이아웃 템플릿의 적용부분 등은 이쪽https://github.com/vitorsvieira/go-gin-boilerplate의 진의 샘플에서 에코로 이식됐다.
기본적으로 리뷰를 보면 알 수 있는 코드로, 처음에는 로드 템플렉스(load Templates)로 사전에 레이아웃 디자인이 적용된 템플릿을 맵에 집어넣고, 템플렉스 #Render()로 맵에서 템플릿을 끌어내 처리한 곳에 초점을 맞췄다.
Go 자신이 최근에 공부하고 있어서 많은 착오가 있을 수 있다.
실행 결과 
GET /
 
 
 
GET /api/hello
 
 
 
향후의 발전 
<html>
  <head>
    <title>Echo HTML Server Sample</title>
  </head>
  <body>
    <!-- Render the current template here -->
    {{template "content" .}}
  </body>
</html>
{{define "content"}}
<h2>Hello {{.}}!</h2>
{{end}}
{"hello": "world"}
main.go
package main
import (
    "html/template"
    "io"
    "net/http"
    "github.com/labstack/echo"
    "github.com/labstack/echo/middleware"
)
// レイアウト適用済のテンプレートを保存するmap
var templates map[string]*template.Template
// Template はHTMLテンプレートを利用するためのRenderer Interfaceです。
type Template struct {
}
// Render はHTMLテンプレートにデータを埋め込んだ結果をWriterに書き込みます。
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
    return templates[name].ExecuteTemplate(w, "layout.html", data)
}
func main() {
    // Echoのインスタンスを生成
    e := echo.New()
    // テンプレートを利用するためのRendererの設定
    t := &Template{}
    e.Renderer = t
    // ミドルウェアを設定
    e.Use(middleware.Logger())
    e.Use(middleware.Recover())
    // 静的ファイルのパスを設定
    e.Static("/public/css/", "./public/css")
    e.Static("/public/js/", "./public/js/")
    e.Static("/public/img/", "./public/img/")
    // 各ルーティングに対するハンドラを設定
    e.GET("/", HandleIndexGet)
    e.GET("/api/hello", HandleAPIHelloGet)
    // サーバーを開始
    e.Logger.Fatal(e.Start(":3000"))
}
// 初期化を行います。
func init() {
    loadTemplates()
}
// 各HTMLテンプレートに共通レイアウトを適用した結果を保存します(初期化時に実行)。
func loadTemplates() {
    var baseTemplate = "templates/layout.html"
    templates = make(map[string]*template.Template)
    templates["index"] = template.Must(
        template.ParseFiles(baseTemplate, "templates/hello.html"))
}
// HandleIndexGet は Index のGet時のHTMLデータ生成処理を行います。
func HandleIndexGet(c echo.Context) error {
    return c.Render(http.StatusOK, "index", "World")
}
// HandleAPIHelloGet は /api/hello のGet時のJSONデータ生成処理を行います。
func HandleAPIHelloGet(c echo.Context) error {
    return c.JSON(http.StatusOK, map[string]interface{}{"hello": "world"})
}
기본적으로 리뷰를 보면 알 수 있는 코드로, 처음에는 로드 템플렉스(load Templates)로 사전에 레이아웃 디자인이 적용된 템플릿을 맵에 집어넣고, 템플렉스 #Render()로 맵에서 템플릿을 끌어내 처리한 곳에 초점을 맞췄다.
Go 자신이 최근에 공부하고 있어서 많은 착오가 있을 수 있다.
실행 결과 
GET /
 
 
 
GET /api/hello
 
 
 
향후의 발전 
Reference
이 문제에 관하여(Go 언어의 웹 프레임워크 "Echo"①(Hello World의)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/y_ussie/items/ca8dc5e423eec318a436텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)