Skip to content

Instantly share code, notes, and snippets.

@komagata
Created July 28, 2016 09:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komagata/e772cf5178878877399513c0858640d2 to your computer and use it in GitHub Desktop.
Save komagata/e772cf5178878877399513c0858640d2 to your computer and use it in GitHub Desktop.
go-cache利用アプリ。
package main
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"github.com/patrickmn/go-cache"
"html/template"
"net/http"
"strconv"
"time"
)
var c = cache.New(10*time.Minute, 30*time.Second)
func getValue() string {
var targetId = 100000
var key = strconv.Itoa(targetId)
var pad string
if x, found := c.Get(key); found {
pad = x.(string)
} else {
db, err := sql.Open("mysql", "root@/sbtest")
if err != nil {
panic(err.Error())
}
defer db.Close()
rows, err := db.Query("SELECT pad FROM sbtest WHERE id = " + key)
defer rows.Close()
if err != nil {
panic(err.Error())
}
for rows.Next() {
if err := rows.Scan(&pad); err != nil {
panic(err.Error())
}
}
c.Set(key, pad, cache.DefaultExpiration)
}
return pad
}
func viewHandler(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFiles("index.html")
if err != nil {
panic(err)
}
pad := getValue()
err = tmpl.Execute(w, struct {
Pad string
}{
Pad: pad,
})
if err != nil {
panic(err)
}
}
func main() {
http.HandleFunc("/", viewHandler)
http.ListenAndServe(":8081", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment