Files
wonder 01ecdc8c23 feat: initialize project skeleton with Go backend, database, and config
- Go module with standard library + gorilla/sessions + mysql driver
- Config: env-based configuration with .env file support
- Database: MySQL connection with auto-migration for 6 tables
- Seed data: 12 system tags with options, 8 system snippets
- Auth: session cookie middleware
- Handlers: auth, tags, snippets, builder, claude, dashboard, suggestions, settings
- LLM: OpenAI-compatible client with 30s timeout
- Docker: Dockerfile + docker-compose.yml
- .env.example with all configuration options

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-26 14:58:15 +08:00

70 lines
1.6 KiB
Go

package handlers
import (
"encoding/json"
"net/http"
"prompt-generator/internal/auth"
"prompt-generator/internal/config"
"prompt-generator/internal/models"
)
var cfg *config.Config
func Init(c *config.Config) {
cfg = c
}
func writeJSON(w http.ResponseWriter, code int, resp models.APIResponse) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
json.NewEncoder(w).Encode(resp)
}
func success(w http.ResponseWriter, data interface{}) {
writeJSON(w, http.StatusOK, models.APIResponse{Code: 0, Message: "success", Data: data})
}
func fail(w http.ResponseWriter, httpCode int, msg string) {
writeJSON(w, httpCode, models.APIResponse{Code: httpCode, Message: msg})
}
func Login(w http.ResponseWriter, r *http.Request) {
var req struct {
Password string `json:"password"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
fail(w, 400, "请求格式错误")
return
}
if req.Password != cfg.AuthPassword {
fail(w, 401, "密码错误")
return
}
session, _ := auth.Store.Get(r, "session")
session.Values["authenticated"] = true
session.Save(r, w)
success(w, nil)
}
func Logout(w http.ResponseWriter, r *http.Request) {
session, _ := auth.Store.Get(r, "session")
session.Values["authenticated"] = false
session.Options.MaxAge = -1
session.Save(r, w)
success(w, nil)
}
func AuthCheck(w http.ResponseWriter, r *http.Request) {
session, _ := auth.Store.Get(r, "session")
authed, ok := session.Values["authenticated"].(bool)
if !ok || !authed {
fail(w, 401, "未登录")
return
}
success(w, map[string]bool{"authenticated": true})
}