Created
July 28, 2016 09:50
-
-
Save komagata/e772cf5178878877399513c0858640d2 to your computer and use it in GitHub Desktop.
go-cache利用アプリ。
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" | |
_ "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