Created
August 12, 2014 15:43
-
-
Save akira093/9081e3e890b592623608 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"database/sql" | |
"fmt" | |
"net/http" | |
"github.com/go-martini/martini" | |
_ "github.com/mattn/go-sqlite3" | |
"html/template" | |
) | |
var temp = ` | |
<h1>greetings</h1> | |
{{range .}} | |
<blockquote> | |
name: {{.Name}}<br> | |
comment {{.Comment}} | |
</blockquote> | |
{{end}} | |
` | |
type Greeting struct { | |
Id int | |
Name string | |
Comment string | |
} | |
func GetGreetings() []Greeting { | |
db, err := sql.Open("sqlite3", "./grs.db") | |
if err != nil { | |
panic(err) | |
} | |
rows, err := db.Query(`select * from Greetings`) | |
if err != nil { | |
panic(err) | |
} | |
grs := make([]Greeting, 0, 100) | |
for rows.Next() { | |
var gr Greeting | |
rows.Scan(&gr.Id, &gr.Name, &gr.Comment) | |
grs = append(grs, gr) | |
} | |
rows.Close() | |
return grs | |
} | |
func root(w http.ResponseWriter, r *http.Request) { | |
t := template.New("some template") //テンプレートを新規に作成する。 | |
t, _ = t.Parse(temp) //テンプレートファイルを解析 | |
grs := GetGreetings() //テーブルを読む | |
fmt.Println(grs) | |
t.Execute(w, grs) //テンプレートのmerger操作を実行する。 | |
} | |
func main() { | |
m := martini.Classic() | |
m.Get("/", root) | |
m.Run() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment