import文とは?
状態:-
閲覧数:278
投稿日:2018-03-26
更新日:2018-04-11
他パッケージのメンバへアクセスするために使用
GO PATHのsrcディレクトリ直下をベースとして、srcディレクトリ内のディレクトリを相対パス指定する
・指定されたディレクトリ直下のコードのパッケージ名を読み込む
import文 / import文の正確な挙動
import文
他パッケージのメンバへアクセスするためには、import文を使用
・ import文によって読み込んだパッケージのメンバへのアクセスは、パッケージ名.メンバ名という形で行う
import (
"html/template"
template.ParseFiles(baseTemplate, "templates/hello.html"))
import (
"io"
w io.Writer
import (
"net/http"
http.StatusOK
import (
"github.com/labstack/echo"
echo.New()
import (
"github.com/labstack/echo/middleware"
middleware.Logger()
コード
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"})
}
import文の正確な挙動
「GOPATHのsrcディレクトリ直下」をベースとして、「srcディレクトリ内のディレクトリ」を「相対パス指定」する
・import文は「指定されたディレクトリ直下のコード」の「パッケージ名」を読み込む
→ 「import文に指定した文字列」と「読み込まれるパッケージ名」が一致しないケースがある
一致しない具体例
$GOPATH/
┗src/
┣a/
┃┣h/
┃┃┗h.go(パッケージ名:h)
┃┣i/
┃┃┗i.go(パッケージ名:v)
┃┗a.go(パッケージ名:a)
┗b/
┗a.go(パッケージ名:w)
┗src/
┣a/
┃┣h/
┃┃┗h.go(パッケージ名:h)
┃┣i/
┃┃┗i.go(パッケージ名:v)
┃┗a.go(パッケージ名:a)
┗b/
┗a.go(パッケージ名:w)
import文と参照時のパッケージ名は以下の様になる
import "a" // パッケージ名: a
import "b" // パッケージ名: w
import "a/h" // パッケージ名: h
import "a/i" // パッケージ名: v
import "b" // パッケージ名: w
import "a/h" // パッケージ名: h
import "a/i" // パッケージ名: v
・Goの「ファイル名」と「パッケージ名」について