|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "log" |
| 6 | + "net/http" |
| 7 | + "os" |
| 8 | + "strconv" |
| 9 | + |
| 10 | + "github.com/syumai/workers" |
| 11 | +) |
| 12 | + |
| 13 | +// counterNamespace is a bounded KV namespace for storing counter. |
| 14 | +const counterNamespace = "COUNTER" |
| 15 | + |
| 16 | +// countKey is a key to store current count value to the KV namespace. |
| 17 | +const countKey = "count" |
| 18 | + |
| 19 | +func handleErr(w http.ResponseWriter, msg string, err error) { |
| 20 | + log.Println(err) |
| 21 | + w.WriteHeader(http.StatusInternalServerError) |
| 22 | + w.Write([]byte(msg)) |
| 23 | +} |
| 24 | + |
| 25 | +func main() { |
| 26 | + // initialize KV namespace instance |
| 27 | + kv, err := workers.NewKVNamespace(counterNamespace) |
| 28 | + if err != nil { |
| 29 | + fmt.Fprintf(os.Stderr, "failed to init KV: %v", err) |
| 30 | + os.Exit(1) |
| 31 | + } |
| 32 | + |
| 33 | + http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { |
| 34 | + if req.URL.Path != "/" { |
| 35 | + w.WriteHeader(http.StatusNotFound) |
| 36 | + return |
| 37 | + } |
| 38 | + |
| 39 | + countStr, err := kv.GetString(countKey, nil) |
| 40 | + if err != nil { |
| 41 | + handleErr(w, "failed to get current count\n", err) |
| 42 | + return |
| 43 | + } |
| 44 | + |
| 45 | + /* |
| 46 | + countReader, err := kv.GetReader(countKey, nil) |
| 47 | + if err != nil { |
| 48 | + handleErr(w, "failed to get current count\n", err) |
| 49 | + return |
| 50 | + } |
| 51 | + b, _ := io.ReadAll(countReader) |
| 52 | + countStr := string(b) |
| 53 | + */ |
| 54 | + |
| 55 | + // ignore err and treat count value as 0 |
| 56 | + count, _ := strconv.Atoi(countStr) |
| 57 | + |
| 58 | + nextCountStr := strconv.Itoa(count + 1) |
| 59 | + |
| 60 | + err = kv.PutString(countKey, nextCountStr, nil) |
| 61 | + if err != nil { |
| 62 | + handleErr(w, "failed to put next count\n", err) |
| 63 | + return |
| 64 | + } |
| 65 | + |
| 66 | + /* |
| 67 | + err = kv.PutReader(countKey, strings.NewReader(nextCountStr), nil) |
| 68 | + if err != nil { |
| 69 | + handleErr(w, "failed to put next count\n", err) |
| 70 | + return |
| 71 | + } |
| 72 | + */ |
| 73 | + |
| 74 | + w.Header().Set("Content-Type", "text/plain") |
| 75 | + |
| 76 | + /* |
| 77 | + // List returns only `count` as the keys in this namespace. |
| 78 | + v, err := kv.List(nil) |
| 79 | + if err != nil { |
| 80 | + handleErr(w, "failed to list\n", err) |
| 81 | + return |
| 82 | + } |
| 83 | + for i, key := range v.Keys { |
| 84 | + fmt.Fprintf(w, "%d: %s\n", i, key.Name) |
| 85 | + } |
| 86 | + */ |
| 87 | + |
| 88 | + w.Write([]byte(nextCountStr)) |
| 89 | + }) |
| 90 | + |
| 91 | + workers.Serve(nil) |
| 92 | +} |
0 commit comments