63 lines
1.3 KiB
Go
Raw Permalink Normal View History

2022-07-31 18:36:16 +09:00
package main
import (
"fmt"
"log"
"net/http"
"os"
"strconv"
"github.com/syumai/workers"
2023-02-11 12:37:38 +09:00
"github.com/syumai/workers/cloudflare"
2022-07-31 18:36:16 +09:00
)
// counterNamespace is a bounded KV namespace for storing counter.
const counterNamespace = "COUNTER"
// countKey is a key to store current count value to the KV namespace.
const countKey = "count"
func handleErr(w http.ResponseWriter, msg string, err error) {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(msg))
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
if req.URL.Path != "/" {
w.WriteHeader(http.StatusNotFound)
return
}
2023-02-11 12:37:38 +09:00
// initialize KV namespace instance
2024-04-17 00:56:47 +09:00
kv, err := cloudflare.NewKVNamespace(counterNamespace)
2023-02-11 12:37:38 +09:00
if err != nil {
fmt.Fprintf(os.Stderr, "failed to init KV: %v", err)
os.Exit(1)
}
2022-07-31 18:36:16 +09:00
countStr, err := kv.GetString(countKey, nil)
if err != nil {
handleErr(w, "failed to get current count\n", err)
return
}
// ignore err and treat count value as 0
count, _ := strconv.Atoi(countStr)
nextCountStr := strconv.Itoa(count + 1)
err = kv.PutString(countKey, nextCountStr, nil)
if err != nil {
handleErr(w, "failed to put next count\n", err)
return
}
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte(nextCountStr))
})
workers.Serve(nil)
}