This commit is contained in:
2026-01-22 22:42:10 +08:00
commit 7ff66a7cc2
8 changed files with 1012 additions and 0 deletions

7
.gitignore vendored Normal file
View File

@@ -0,0 +1,7 @@
.vscode
.idea
.DS_Store
.env

39
README.md Normal file
View File

@@ -0,0 +1,39 @@
# Simple Todo API (Demo)
This is a minimal, runnable RESTful API aligned with the plan. It uses Gin and an in-memory store.
## Run
```bash
go run ./main.go
```
The server listens on `:8080`.
## Frontend
The UI is served from local files under `test/web` at `/`:
```bash
open http://localhost:8080/api
```
## Quick Demo
```bash
curl http://localhost:8080/api/health
curl -X POST http://localhost:8080/api/v1/auth/login
curl -X POST http://localhost:8080/api/v1/tasks \
-H 'Authorization: Bearer demo' \
-H 'Content-Type: application/json' \
-d '{"title":"Learn Gin","priority":1,"tags":["demo"]}'
curl http://localhost:8080/api/v1/tasks \
-H 'Authorization: Bearer demo'
```
## Notes
- Data is in-memory only; restart will clear it.
- Auth is a placeholder; any non-empty `Authorization` header is accepted.

34
go.mod Normal file
View File

@@ -0,0 +1,34 @@
module wolves.top/todo
go 1.25.5
require github.com/gin-gonic/gin v1.10.0
require (
github.com/bytedance/sonic v1.11.6 // indirect
github.com/bytedance/sonic/loader v0.1.1 // indirect
github.com/cloudwego/base64x v0.1.4 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.20.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/crypto v0.23.0 // indirect
golang.org/x/net v0.25.0 // indirect
golang.org/x/sys v0.20.0 // indirect
golang.org/x/text v0.15.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

89
go.sum Normal file
View File

@@ -0,0 +1,89 @@
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=

334
main.go Normal file
View File

@@ -0,0 +1,334 @@
package main
import (
"net/http"
"strconv"
"sync"
"time"
"github.com/gin-gonic/gin"
)
type Task struct {
ID int64 `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
Status string `json:"status"`
DueAt string `json:"due_at"`
Priority int `json:"priority"`
Tags []string `json:"tags"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type taskStore struct {
mu sync.Mutex
nextID int64
items map[int64]Task
}
type User struct {
ID int64 `json:"id"`
Email string `json:"email"`
Password string `json:"-"`
}
type authStore struct {
mu sync.Mutex
nextID int64
users map[string]User
sessions map[string]int64
}
func newTaskStore() *taskStore {
return &taskStore{
nextID: 1,
items: make(map[int64]Task),
}
}
func newAuthStore() *authStore {
return &authStore{
nextID: 1,
users: make(map[string]User),
sessions: make(map[string]int64),
}
}
func (s *authStore) register(email, password string) (User, bool) {
s.mu.Lock()
defer s.mu.Unlock()
if _, exists := s.users[email]; exists {
return User{}, false
}
user := User{
ID: s.nextID,
Email: email,
Password: password,
}
s.nextID++
s.users[email] = user
return user, true
}
func (s *authStore) login(email, password string) (string, bool) {
s.mu.Lock()
defer s.mu.Unlock()
user, ok := s.users[email]
if !ok || user.Password != password {
return "", false
}
token := strconv.FormatInt(time.Now().UnixNano(), 36) + "-" + strconv.FormatInt(user.ID, 10)
s.sessions[token] = user.ID
return token, true
}
func (s *authStore) validate(token string) bool {
s.mu.Lock()
defer s.mu.Unlock()
_, ok := s.sessions[token]
return ok
}
func (s *taskStore) list() []Task {
s.mu.Lock()
defer s.mu.Unlock()
result := make([]Task, 0, len(s.items))
for _, t := range s.items {
result = append(result, t)
}
return result
}
func (s *taskStore) get(id int64) (Task, bool) {
s.mu.Lock()
defer s.mu.Unlock()
t, ok := s.items[id]
return t, ok
}
func (s *taskStore) create(input Task) Task {
s.mu.Lock()
defer s.mu.Unlock()
input.ID = s.nextID
s.nextID++
now := time.Now().UTC()
input.CreatedAt = now
input.UpdatedAt = now
if input.Status == "" {
input.Status = "todo"
}
s.items[input.ID] = input
return input
}
func (s *taskStore) update(id int64, input Task) (Task, bool) {
s.mu.Lock()
defer s.mu.Unlock()
existing, ok := s.items[id]
if !ok {
return Task{}, false
}
if input.Title != "" {
existing.Title = input.Title
}
if input.Description != "" {
existing.Description = input.Description
}
if input.Status != "" {
existing.Status = input.Status
}
if input.DueAt != "" {
existing.DueAt = input.DueAt
}
if input.Priority != 0 {
existing.Priority = input.Priority
}
if input.Tags != nil {
existing.Tags = input.Tags
}
existing.UpdatedAt = time.Now().UTC()
s.items[id] = existing
return existing, true
}
func (s *taskStore) delete(id int64) bool {
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.items[id]; !ok {
return false
}
delete(s.items, id)
return true
}
func main() {
store := newTaskStore()
authStore := newAuthStore()
gin.SetMode(gin.DebugMode)
router := gin.Default()
router.RedirectTrailingSlash = false
router.RedirectFixedPath = false
router.Use(func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
if c.Request.Method == http.MethodOptions {
c.AbortWithStatus(http.StatusNoContent)
return
}
c.Next()
})
router.GET("/api/health", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
router.GET("/", func(c *gin.Context) {
c.File("test/web/index.html")
})
router.GET("/styles.css", func(c *gin.Context) {
c.File("test/web/styles.css")
})
router.GET("/app.js", func(c *gin.Context) {
c.File("test/web/app.js")
})
auth := router.Group("/api/v1/auth")
{
auth.POST("/register", func(c *gin.Context) {
var input struct {
Email string `json:"email"`
Password string `json:"password"`
}
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if input.Email == "" || input.Password == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "email and password required"})
return
}
user, ok := authStore.register(input.Email, input.Password)
if !ok {
c.JSON(http.StatusConflict, gin.H{"error": "user already exists"})
return
}
c.JSON(http.StatusCreated, gin.H{"id": user.ID, "email": user.Email})
})
auth.POST("/login", func(c *gin.Context) {
var input struct {
Email string `json:"email"`
Password string `json:"password"`
}
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if input.Email == "" || input.Password == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "email and password required"})
return
}
token, ok := authStore.login(input.Email, input.Password)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"})
return
}
c.JSON(http.StatusOK, gin.H{"token": token})
})
}
api := router.Group("/api/v1")
api.Use(func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing authorization"})
return
}
token := authHeader
if len(authHeader) > 7 && authHeader[:7] == "Bearer " {
token = authHeader[7:]
}
if token == "" || !authStore.validate(token) {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
return
}
c.Next()
})
tasks := api.Group("/tasks")
{
tasks.GET("", func(c *gin.Context) {
c.JSON(http.StatusOK, store.list())
})
tasks.POST("", func(c *gin.Context) {
var input Task
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
created := store.create(input)
c.JSON(http.StatusCreated, created)
})
tasks.GET(":id", func(c *gin.Context) {
id, err := parseID(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
return
}
task, ok := store.get(id)
if !ok {
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
c.JSON(http.StatusOK, task)
})
tasks.PUT(":id", func(c *gin.Context) {
id, err := parseID(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
return
}
var input Task
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
updated, ok := store.update(id, input)
if !ok {
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
c.JSON(http.StatusOK, updated)
})
tasks.DELETE(":id", func(c *gin.Context) {
id, err := parseID(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
return
}
if !store.delete(id) {
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
c.Status(http.StatusNoContent)
})
}
if err := router.Run(":8080"); err != nil {
panic(err)
}
}
func parseID(value string) (int64, error) {
return strconv.ParseInt(value, 10, 64)
}

150
web/app.js Normal file
View File

@@ -0,0 +1,150 @@
const API_BASE = 'http://localhost:8080/api/v1';
let token = '';
const sessionState = document.getElementById('sessionState');
const loginBtn = document.getElementById('loginBtn');
const createForm = document.getElementById('createForm');
const taskList = document.getElementById('taskList');
const refreshBtn = document.getElementById('refreshBtn');
const clearBtn = document.getElementById('clearBtn');
const template = document.getElementById('taskTemplate');
function setSessionState(text) {
sessionState.textContent = text;
}
function getHeaders() {
return {
'Content-Type': 'application/json',
Authorization: token ? `Bearer ${token}` : '',
};
}
async function login() {
const response = await fetch(`${API_BASE}/auth/login`, {
method: 'POST',
});
if (!response.ok) {
setSessionState('Login failed');
return;
}
const data = await response.json();
token = data.token || 'demo-token';
setSessionState('Connected');
await loadTasks();
}
function buildMeta(task) {
const parts = [];
if (task.status) parts.push(task.status.toUpperCase());
if (task.due_at) parts.push(`Due: ${task.due_at}`);
if (task.priority) parts.push(`P${task.priority}`);
if (task.tags && task.tags.length > 0) parts.push(task.tags.join(', '));
return parts.join(' • ');
}
function renderTasks(tasks) {
taskList.innerHTML = '';
if (!tasks || tasks.length === 0) {
taskList.innerHTML = '<div class="empty">No tasks yet.</div>';
return;
}
tasks.forEach((task) => {
const node = template.content.cloneNode(true);
node.querySelector('h3').textContent = task.title || 'Untitled task';
node.querySelector('.meta').textContent = buildMeta(task);
node.querySelector('.desc').textContent = task.description || '';
node.querySelector('.badge').textContent = task.status || 'todo';
node.querySelector('.toggle').addEventListener('click', () => toggleStatus(task));
node.querySelector('.delete').addEventListener('click', () => deleteTask(task));
taskList.appendChild(node);
});
}
async function loadTasks() {
const response = await fetch(`${API_BASE}/tasks`, {
headers: getHeaders(),
});
if (!response.ok) {
setSessionState('Auth required');
renderTasks([]);
return;
}
const data = await response.json();
renderTasks(data);
}
async function createTask(event) {
event.preventDefault();
const form = new FormData(createForm);
const payload = {
title: form.get('title'),
description: form.get('description'),
due_at: toISO(form.get('due_at')),
priority: Number(form.get('priority') || 0),
tags: String(form.get('tags') || '')
.split(',')
.map((tag) => tag.trim())
.filter(Boolean),
};
const response = await fetch(`${API_BASE}/tasks`, {
method: 'POST',
headers: getHeaders(),
body: JSON.stringify(payload),
});
if (!response.ok) {
setSessionState('Failed to create task');
return;
}
createForm.reset();
await loadTasks();
}
async function toggleStatus(task) {
const nextStatus = task.status === 'done' ? 'todo' : 'done';
await fetch(`${API_BASE}/tasks/${task.id}`, {
method: 'PUT',
headers: getHeaders(),
body: JSON.stringify({ status: nextStatus }),
});
await loadTasks();
}
async function deleteTask(task) {
await fetch(`${API_BASE}/tasks/${task.id}`, {
method: 'DELETE',
headers: getHeaders(),
});
await loadTasks();
}
async function clearCompleted() {
const response = await fetch(`${API_BASE}/api/tasks`, {
headers: getHeaders(),
});
if (!response.ok) {
return;
}
const tasks = await response.json();
const completed = tasks.filter((task) => task.status === 'done');
for (const task of completed) {
await deleteTask(task);
}
}
loginBtn.addEventListener('click', login);
createForm.addEventListener('submit', createTask);
refreshBtn.addEventListener('click', loadTasks);
clearBtn.addEventListener('click', clearCompleted);
setSessionState('Not connected');
function toISO(value) {
if (!value) return '';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return '';
return date.toISOString();
}

92
web/index.html Normal file
View File

@@ -0,0 +1,92 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Todo Control Room</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div class="bg-orbit"></div>
<main class="shell">
<header class="hero">
<div>
<p class="eyebrow">Distributed todo playground</p>
<h1>Todo Control Room</h1>
<p class="subhead">A bold, focused UI to drive your task workflow from a single cockpit.</p>
</div>
<div class="status-card">
<h2>Session</h2>
<p id="sessionState">Not connected</p>
<button id="loginBtn" class="btn primary">Login (demo)</button>
</div>
</header>
<section class="panel">
<div class="panel-head">
<h2>New Task</h2>
<p>Create tasks quickly with priority and due date.</p>
</div>
<form id="createForm" class="form-grid">
<label>
<span>Title</span>
<input type="text" name="title" placeholder="Plan service split" required />
</label>
<label>
<span>Due</span>
<input type="datetime-local" name="due_at" />
</label>
<label>
<span>Priority</span>
<select name="priority">
<option value="1">High</option>
<option value="2">Medium</option>
<option value="3">Low</option>
</select>
</label>
<label>
<span>Tags (comma)</span>
<input type="text" name="tags" placeholder="backend, microservices" />
</label>
<label class="full">
<span>Description</span>
<textarea name="description" placeholder="Outline scope, list risks..."></textarea>
</label>
<button class="btn primary" type="submit">Create Task</button>
</form>
</section>
<section class="panel">
<div class="panel-head">
<h2>Tasks</h2>
<div class="actions">
<button id="refreshBtn" class="btn ghost">Refresh</button>
<button id="clearBtn" class="btn ghost">Clear Completed</button>
</div>
</div>
<div id="taskList" class="task-list">
<div class="empty">No tasks yet.</div>
</div>
</section>
</main>
<template id="taskTemplate">
<article class="task-card">
<div class="task-main">
<div>
<h3></h3>
<p class="meta"></p>
<p class="desc"></p>
</div>
<div class="badge"></div>
</div>
<div class="task-actions">
<button class="btn ghost toggle">Toggle Status</button>
<button class="btn ghost delete">Delete</button>
</div>
</article>
</template>
<script src="app.js"></script>
</body>
</html>

267
web/styles.css Normal file
View File

@@ -0,0 +1,267 @@
@import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=Syne:wght@600;700&display=swap');
:root {
color-scheme: light;
--bg: #f6f3ef;
--bg-alt: #efe7de;
--ink: #1b1a17;
--muted: #6c5f57;
--accent: #d97706;
--accent-dark: #a35503;
--card: #fff7ed;
--stroke: rgba(27, 26, 23, 0.1);
--shadow: 0 24px 60px rgba(27, 26, 23, 0.15);
}
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: 'Space Grotesk', sans-serif;
background: radial-gradient(circle at top, #fff2d9 0%, var(--bg) 40%, var(--bg-alt) 100%);
color: var(--ink);
min-height: 100vh;
overflow-x: hidden;
}
h1, h2, h3 {
font-family: 'Syne', sans-serif;
margin: 0;
}
.bg-orbit {
position: fixed;
inset: 0;
background: radial-gradient(circle at 20% 20%, rgba(217, 119, 6, 0.2), transparent 50%),
radial-gradient(circle at 80% 10%, rgba(30, 64, 175, 0.15), transparent 45%),
radial-gradient(circle at 70% 80%, rgba(190, 24, 93, 0.12), transparent 60%);
z-index: -1;
}
.shell {
max-width: 1080px;
margin: 0 auto;
padding: 48px 24px 80px;
display: flex;
flex-direction: column;
gap: 32px;
}
.hero {
display: grid;
grid-template-columns: minmax(0, 1fr) 280px;
gap: 24px;
align-items: stretch;
}
.eyebrow {
text-transform: uppercase;
letter-spacing: 0.2em;
font-size: 0.72rem;
color: var(--muted);
margin: 0 0 12px;
}
.subhead {
font-size: 1rem;
color: var(--muted);
margin-top: 12px;
max-width: 42ch;
}
.status-card {
background: var(--card);
border: 1px solid var(--stroke);
border-radius: 18px;
padding: 20px;
box-shadow: var(--shadow);
display: flex;
flex-direction: column;
gap: 12px;
}
.status-card p {
margin: 0;
color: var(--muted);
}
.panel {
background: rgba(255, 255, 255, 0.6);
border: 1px solid var(--stroke);
border-radius: 28px;
padding: 28px;
backdrop-filter: blur(6px);
box-shadow: var(--shadow);
animation: floatIn 0.6s ease both;
}
.panel-head {
display: flex;
justify-content: space-between;
align-items: center;
gap: 16px;
margin-bottom: 18px;
}
.panel-head p {
color: var(--muted);
margin: 4px 0 0;
}
.actions {
display: flex;
gap: 12px;
}
.form-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16px 20px;
}
.form-grid label {
display: flex;
flex-direction: column;
gap: 8px;
font-size: 0.85rem;
color: var(--muted);
}
.form-grid input,
.form-grid select,
.form-grid textarea {
border-radius: 12px;
border: 1px solid var(--stroke);
padding: 12px 14px;
font-size: 0.95rem;
font-family: inherit;
background: #fff;
}
.form-grid textarea {
min-height: 90px;
resize: vertical;
}
.form-grid .full {
grid-column: 1 / -1;
}
.btn {
border-radius: 999px;
padding: 10px 18px;
border: 1px solid transparent;
cursor: pointer;
font-weight: 600;
font-family: inherit;
transition: transform 0.15s ease, box-shadow 0.15s ease;
}
.btn.primary {
background: var(--accent);
color: #fff;
box-shadow: 0 12px 24px rgba(217, 119, 6, 0.3);
}
.btn.ghost {
background: transparent;
border: 1px solid var(--stroke);
color: var(--ink);
}
.btn:hover {
transform: translateY(-2px);
}
.task-list {
display: grid;
gap: 16px;
}
.task-card {
background: var(--card);
border-radius: 20px;
padding: 18px;
border: 1px solid var(--stroke);
display: flex;
flex-direction: column;
gap: 14px;
animation: riseIn 0.4s ease both;
}
.task-main {
display: flex;
justify-content: space-between;
gap: 16px;
align-items: flex-start;
}
.task-card h3 {
margin: 0 0 6px;
}
.task-card .meta {
font-size: 0.85rem;
color: var(--muted);
}
.task-card .desc {
margin: 6px 0 0;
}
.badge {
padding: 6px 12px;
border-radius: 999px;
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.1em;
background: rgba(217, 119, 6, 0.15);
color: var(--accent-dark);
}
.task-actions {
display: flex;
gap: 12px;
}
.empty {
padding: 20px;
border: 1px dashed var(--stroke);
border-radius: 16px;
text-align: center;
color: var(--muted);
}
@keyframes floatIn {
from {
opacity: 0;
transform: translateY(24px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes riseIn {
from {
opacity: 0;
transform: translateY(12px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@media (max-width: 900px) {
.hero {
grid-template-columns: 1fr;
}
.form-grid {
grid-template-columns: 1fr;
}
}