2016-07-18 4 views
0

私はGolangに新しく、いくつかのチュートリアルを続けていましたが、私はウェブサイトを作成するために学んだことを実践したいですこれはmain.goファイルですデータベースとしてmysqlを使用してこのGolang Webアプリケーションのヘルプが必要です

package main 

import (
     "html/template" 
     "net/http" 
     "log" 
     "database/sql" 
     _"github.com/go-sql-driver/mysql" 
) 

//Fetch all templates 
var templates, templatesErr = template.ParseGlob("templates/*") 
func main() { 
    PORT := ":9000" 
    log.Println("Listening to port", PORT) 
    http.HandleFunc("/", root) 
    http.HandleFunc("/facilities", allFacilities) 
    http.ListenAndServe(PORT, nil) 

} 
func root(w http.ResponseWriter, r *http.Request) { 
    rootData := make(map[string]string) 
    rootData["page_title"] = "iSpace Open Data" 
    rootData["body"] = "" 

    templates.ExecuteTemplate(w, "index.html", rootData) 
} 

type facility struct{ 
    FacilityName string 
    Type string 
} 

func allFacilities(w http.ResponseWriter, r *http.Request){ 
    db, err := sql.Open("mysql", "root:[email protected](127.0.0.1:3306)/iod") 
    if err !=nil{ 
    log.Fatal(err) 
    } 
    defer db.Close() 
    rows, err := db.Query("Select FacilityName, Type from health_facilities ") 
    if err != nil { 
     log.Fatal(err) 
    } 
    defer rows.Close() 

    fac := facility{} 
    facilities := []facility{} 
    for rows.Next(){ 
    var FacilityName, Type string 
    rows.Scan(&FacilityName, &Type) 
    fac.FacilityName= FacilityName 
    fac.Type= Type 
    facilities = append(facilities, fac) 
    } 
    templates.ExecuteTemplate(w, "facilities.html", facilities) 
} 

これは、ビューのテンプレートフォルダにhtmlファイルを使用します。しかし、私はそれがポインタ逆参照を持っていると言ってランタイムエラーを取得し続けます。私は助けてください。

+0

エラーが発生するのはどの行ですか? – TehSphinX

+0

スタックトレース出力はエラーがどこにあるかを正確に示します。あなたのコードのどの行がパニックに陥っていて、コールスタックは何ですか? – JimB

+0

main.goが存在するのと同じディレクトリにtemplates/index.htmlがあるかどうか確認してください。 –

答えて

0

コードを試しても同じエラーが発生しました。

templates.ExecuteTemplate(w, "index.html", rootData) 

問題はテンプレートが正しく読み込まれないことです。私は主な関数にテンプレートの解析を移動し、それは動作します。関連するコードスニペット:

//Fetch all templates 
var (
    templates *template.Template 
) 

func main() { 
    var err error 
    templates, err = template.ParseGlob("templates/*") 
    if err != nil { 
     panic(err) 
    } 

    PORT := ":9000" 
    log.Println("Listening to port", PORT) 
    http.HandleFunc("/", root) 
    http.HandleFunc("/facilities", allFacilities) 
    http.ListenAndServe(PORT, nil) 

} 
+0

ありがとう、完璧に動作します –

関連する問題