私は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ファイルを使用します。しかし、私はそれがポインタ逆参照を持っていると言ってランタイムエラーを取得し続けます。私は助けてください。
エラーが発生するのはどの行ですか? – TehSphinX
スタックトレース出力はエラーがどこにあるかを正確に示します。あなたのコードのどの行がパニックに陥っていて、コールスタックは何ですか? – JimB
main.goが存在するのと同じディレクトリにtemplates/index.htmlがあるかどうか確認してください。 –