Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- _ "github.com/mattn/go-sqlite3"
- "net/http"
- "strconv"
- "database/sql"
- "os/signal"
- "time"
- )
- var getPageCountSQL, setPageCountSQL *sql.Stmt
- func main() {
- db,err := sql.Open("sqlite3","test.db")
- if err != nil {
- panic(err.Error())
- }
- defer db.Close()
- db.Exec("CREATE TABLE test (pageCount INT)") // Hopefully, only fails if table already exists.
- // Pre-prepare SQL statements for max speed
- if getPageCountSQL,err = db.Prepare("SELECT pageCount FROM test ORDER BY pageCount DESC") ; err != nil {
- panic(err.Error())
- }
- if setPageCountSQL,err = db.Prepare("INSERT INTO test (pageCount) VALUES (?)") ; err != nil {
- panic(err.Error())
- }
- http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
- count := 0
- if err := getPageCountSQL.QueryRow().Scan(&count) ; err != nil && err != sql.ErrNoRows {
- panic(err.Error())
- }
- // Simulate processing
- time.Sleep(1e9)
- count++
- w.Write([]byte("<html><form method=\"post\"><input type=\"submit\" value=\"Again\"/></form>Page view count: "+strconv.Itoa(count)+"</html>"))
- if _,err := setPageCountSQL.Exec(count) ; err != nil {
- panic(err.Error())
- }
- })
- go http.ListenAndServe(":7777", nil)
- <-signal.Incoming // Exit on kill signal
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement