Skip to content

Instantly share code, notes, and snippets.

@yukidarake
Last active August 29, 2015 14:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yukidarake/06aeb00fe539bde26698 to your computer and use it in GitHub Desktop.
Save yukidarake/06aeb00fe539bde26698 to your computer and use it in GitHub Desktop.
#2
package main
import (
"database/sql"
"net/http"
"github.com/go-martini/martini"
_ "github.com/lib/pq"
"github.com/martini-contrib/render"
)
func setupDB() *sql.DB {
db, err := sql.Open("postgres", "dbname=lesson4 sslmode=disable")
panicIf(err)
return db
}
func panicIf(err error) {
if err != nil {
panic(err)
}
}
func main() {
m := martini.Classic()
m.Use(render.Renderer())
m.Map(setupDB())
m.Get("/hello", func() string {
return "Hello world3!"
})
m.Get("/json1", func(rw http.ResponseWriter) string {
rw.Header().Set("Content-Type", "application/json")
return `
{
"hello": "world",
"test": {
"hoge": 1111
}
}
`
})
m.Get("/json2", func(r render.Render) {
r.JSON(200, map[string]interface{}{
"hello": "world",
"test": map[string]interface{}{
"hoge": 1111,
},
})
})
m.Get("/", func(req *http.Request, rw http.ResponseWriter, r render.Render, db *sql.DB) {
search := "%" + req.URL.Query().Get("search") + "%"
rows, err := db.Query(`SELECT title, author, description
FROM books
WHERE title ILIKE $1
OR author ILIKE $1
OR description ILIKE $1`, search)
panicIf(err)
defer rows.Close()
var title, author, description string
var results []map[string]interface{}
for rows.Next() {
err := rows.Scan(&title, &author, &description)
panicIf(err)
results = append(results, map[string]interface{}{
"Title": title,
"Author": author,
"Description": description,
})
}
r.JSON(200, results)
})
m.Run()
}

使えそうなツールのご紹介

リンク集

Webフレームワークはこの辺から選ぶ
https://github.com/avelino/awesome-go#web-frameworks

(多分)WAFのデファクトスタンダードmartini

https://github.com/go-martini/martini

自動的に再起動してくれるツールgin

https://github.com/codegangsta/gin

まとまっている

http://yuroyoro.hatenablog.com/entry/2014/06/15/173043

ライブコーディング

参考URL

https://gophercasts.io/lessons/4-postgres-basics

まずnet/http

https://github.com/golang-samples/http/blob/master/handlefunc/main.go

コマンド

brew install postgresql

ghq get https://github.com/GopherCasts/Lessons
# git clone https://github.com/GopherCasts/Lessons
cd $GOPATH/src/github.com/GopherCasts/Lessons/lesson4
createdb lesson4 -E utf8
psql lesson4 -f data.sql

go get github.com/codegangsta/gin
go get github.com/go-martini/martini
go get github.com/martini-contrib/render
go get github.com/lib/pq

どういう構成で勝負するか?

Benchmarking Nginx with Go
https://gist.github.com/hgfischer/7965620

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment