Go言語でWebサイトを作ってみる

学習

一覧

 状態:-  閲覧数:904  投稿日:2017-12-17  更新日:2017-12-17
echoで出力結果をブラウザ表示するまで

12/17
・テンプレート使用 / Go言語のWebフレームワーク「Echo」を使ってみる ①(Hello World的な)
・ブラウザ画面
Hello World!


テンプレート使用 / Go言語のWebフレームワーク「Echo」を使ってみる ①(Hello World的な)

 閲覧数:295 投稿日:2017-12-17 更新日:2017-12-27

ディレクトリ構成


▼\home\★★\go\src\try-using-echo\chapter-1\main.go
┏main.go
┗templates/
  ┣hello.html
  ┗layout.html

コード


▼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"})
}


▼templates/layout.html
<html>
 <head>
   <title>Echo HTML Server Sample</title>
 </head>
 <body>
   <!-- Render the current template here -->
   {{template "content" .}}
 </body>


▼templates/hello.html
{{define "content"}}
<h2>Hello {{.}}!</h2>
{{end}}


ブラウザ表示


$ cd /home/★★/go/src/try-using-echo/chapter-1
$ go run main.go

  ____    __
 / __/___/ /  ___
/ _// __/ _ \/ _ \
/___/\__/_//_/\___/ v3.2.5
High performance, minimalist Go web framework
https://echo.labstack.com
____________________________________O/_______
                                   O\
⇨ http server started on [::]:☆☆


ブラウザで「http://グローバルIPアドレス:☆☆」へアクセス
・GET /
・テンプレートを使用して生成したHTMLを返す
Hello World!

ブラウザで「http://グローバルIPアドレス:☆☆/api/hello」へアクセス
・GET /
・以下のJSONを返す
{"hello":"world"}


テンプレート使用 / Go言語のWebフレームワーク「Echo」を使ってみる ①(Hello World的な) / static。CSS反映

 閲覧数:314 投稿日:2017-12-26 更新日:2017-12-30

ディレクトリ構成


▼\home\★★\go\src\try-using-echo\chapter-1\main.go
┏main.go
┣public/
┃ ┗css/
┃  ┗style.css
┗templates/
  ┣hello.html
  ┗layout.html

コード


▼main.go
//中略

//静的ファイルのパスを設定
e.Static("/public/css", "public/css")
e.Static("/public/js", "public/js")
e.Static("/public/img", "public/img")


▼templates/layout.html
<html>
 <head>
   <title>Echo HTML Server Sample</title>
   <link href="public/css/style.css" rel="stylesheet">
 </head>
 <body>
   <!-- Render the current template here -->
   {{template "content" .}}
 </body>


▼public\css\style.css
a {
 text-decoration: none
}
html,body,ul{
 margin: 0;
 padding: 0;
}
ul {
 list-style: none
}
fieldset {
 border: 0;
}
input[type="text"]{
 box-sizing: border-box;
 width: 100%;
 padding: 0.5rem;
}
textarea {
 box-sizing: border-box;
 width: 100%;
}
body{
 background-color:yellow;
}


ブラウザ表示


$ cd /home/★★/go/src/try-using-echo/chapter-1
$ go run main.go

  ____    __
 / __/___/ /  ___
/ _// __/ _ \/ _ \
/___/\__/_//_/\___/ v3.2.5
High performance, minimalist Go web framework
https://echo.labstack.com
____________________________________O/_______
                                   O\
⇨ http server started on [::]:☆☆


ブラウザで「http://グローバルIPアドレス:☆☆」へアクセス
・GET /
・「CSSを読み込んだテンプレート」を使用して生成したHTMLを返す
Hello World!

ブラウザで「http://グローバルIPアドレス:☆☆/public/css/style.css」へアクセス
・GET /public/css/style.css
・静的ファイルを返す


Go言語のWebフレームワーク「Echo」を使ってみる ①(Hello World的な)

2.フォーム画面よりGET送信。リクエストパラメータの扱い

 閲覧数:292 投稿日:2017-12-31 更新日:2018-01-15

コード


フォーム表示のハンドラ
・HandleHelloFormGet()

POST用のハンドラ
・HandleHelloPost()
・HandleAPIHelloPost()

クエリーパラメータ処理を追記
・HandleHelloGet()
・HandleAPIHelloGet()

クエリーパラメータを取得
・echo.Context#QueryParam()

フォームパラメータのPOSTを受ける処理
・HandleHelloPost()

▼main.go
//中略


// 各ルーティングに対するハンドラを設定
e.GET("/", HandleIndexGet)
e.GET("/hello", HandleHelloGet)
e.POST("/hello", HandleHelloPost)
e.GET("/hello_form", HandleHelloFormGet)
e.GET("/api/hello", HandleAPIHelloGet)
e.POST("/api/hello", HandleAPIHelloPost)


//中略


// 各HTMLテンプレートに共通レイアウトを適用した結果を保存します(初期化時に実行)。
func loadTemplates() {
   var baseTemplate = "templates/layout.html"
   templates = make(map[string]*template.Template)
   templates["hello"] = template.Must(
       template.ParseFiles(baseTemplate, "templates/hello.html"))
   templates["hello_form"] = template.Must(
       template.ParseFiles(baseTemplate, "templates/hello_form.html"))
}

// HandleIndexGet は Index のGet時のHTMLデータ生成処理を行います。
func HandleIndexGet(c echo.Context) error {
   return c.Render(http.StatusOK, "hello", "world")
}

// HandleHelloGet は /hello のGet時のHTMLデータ生成処理を行います。
func HandleHelloGet(c echo.Context) error {
   greetingto := c.QueryParam("greetingto")
   return c.Render(http.StatusOK, "hello", greetingto)
}

// HandleHelloPost は /hello のPost時のHTMLデータ生成処理を行います。
func HandleHelloPost(c echo.Context) error {
   greetingto := c.FormValue("greetingto")
   return c.Render(http.StatusOK, "hello", greetingto)
}

// HandleHelloFormGet は /hello_form のGet時のHTMLデータ生成処理を行います。
func HandleHelloFormGet(c echo.Context) error {
   return c.Render(http.StatusOK, "hello_form", nil)
}

// HandleAPIHelloGet は /api/hello のGet時のJSONデータ生成処理を行います。
func HandleAPIHelloGet(c echo.Context) error {
   greetingto := c.QueryParam("greetingto")
   return c.JSON(http.StatusOK, map[string]interface{}{"hello": greetingto})
}

// HelloParam は /api/hello が受けとるJSONパラメータを定義します。
type HelloParam struct {
   GreetingTo string `json:"greetingto"`
}

// HandleAPIHelloPost は /api/hello のPost時のJSONデータ生成処理を行います。
func HandleAPIHelloPost(c echo.Context) error {
   param := new(HelloParam)
   if err := c.Bind(param); err != nil {
       return err
   }
   return c.JSON(http.StatusOK, map[string]interface{}{"hello": param.GreetingTo})
}


▼template/hello_form.html
{{define "content"}}
<form action="/hello" method="POST">
   <label for="greetingto">Greeting To: </label>
   <input type="text" id="greetingto" name="greetingto" />
   <input type="submit" />
</form>
{{end}}


実行


$ cd /home/★★/go/src/try-using-echo/chapter-2
$ go run main.go

  ____    __
 / __/___/ /  ___
/ _// __/ _ \/ _ \
/___/\__/_//_/\___/ v3.2.5
High performance, minimalist Go web framework
https://echo.labstack.com
____________________________________O/_______
                                   O\
⇨ http server started on [::]:☆☆


ブラウザ表示GET /hello?greetingto=xxx


クエリーパラメータで受け取った「greetingto」パラメータをテンプレートに埋め込み、「Hello xxx!」文字列をHTMLで出力する

・ブラウザで「http://グローバルIPアドレス:☆☆/hello?greetingto=xxx」へアクセス
Hello xxx!

・ブラウザで「http://グローバルIPアドレス:☆☆/hello?greetingto=brown」へアクセス
Hello brown!

・ブラウザで「http://グローバルIPアドレス:☆☆/hello?greetingto=%E4%BD%90%E8%97%A4」へアクセス
Hello 佐藤!

ブラウザ表示GET /api/hello?greetingto=xxx


クエリーパラメータで受け取った「greetingto」パラメータより、以下のJSONを返す

・ブラウザで「http://グローバルIPアドレス:☆☆/api/hello?greetingto=xxx」へアクセス
{"hello":"xxx"}

・ブラウザで「http://グローバルIPアドレス:☆☆/api/hello?greetingto=brown」へアクセス
{"hello":"brown"}

・ブラウザで「http://グローバルIPアドレス:☆☆/api/hello?greetingto=%E4%BD%90%E8%97%A4」へアクセス
{"hello":"佐藤"}

ブラウザ表示GET /hello_form


フォーム入力欄を画面出力する
・ブラウザで「http://グローバルIPアドレス:☆☆/hello_form」へアクセス
・画面表示内容
Greeting To:フォーム入力欄「送信」

ブラウザ表示POST /hello


hello_formよりPOSTされた「greetingto」パラメータをテンプレートに埋め込み、Hello xxx!の文字列をHTMLで出力する

ブラウザで「http://グローバルIPアドレス:☆☆/hello_form」へアクセス
「Golang」と入力後、送信ボタンクリック
・「http://グローバルIPアドレス:ポート番号/hello」へ画面遷移
・画面表示
Hello Golang!

ブラウザで「http://グローバルIPアドレス:☆☆/hello_form」へアクセス
「佐藤」と入力後、送信ボタンクリック
・「http://グローバルIPアドレス:ポート番号/hello」へ画面遷移
・画面表示
Hello 佐藤!


Go言語のWebフレームワーク「Echo」を使ってみる ②(リクエストパラメータの扱い)


echoで出力結果をブラウザ表示するまで

Goだけで作るフロントエンド