creating and deleting users

This commit is contained in:
2025-03-11 18:56:12 +02:00
parent 806b27d955
commit 5618aeb439
8 changed files with 132 additions and 34 deletions

View File

@@ -0,0 +1,19 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.28.0
// source: DeleteAllUsers.sql
package database
import (
"context"
)
const deleteAllUser = `-- name: DeleteAllUser :exec
DELETE FROM users WHERE true
`
func (q *Queries) DeleteAllUser(ctx context.Context) error {
_, err := q.db.ExecContext(ctx, deleteAllUser)
return err
}

View File

@@ -0,0 +1,15 @@
package httpResponse
import (
"log"
"net/http"
)
func HTMLHandler(w http.ResponseWriter, status int, text string) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(status)
_, err := w.Write([]byte(text))
if err != nil {
log.Default().Println(err)
}
}

View File

@@ -0,0 +1,15 @@
package httpResponse
import (
"log"
"net/http"
)
func JSONHandler(w http.ResponseWriter, status int, text string) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_, err := w.Write([]byte(text))
if err != nil {
log.Default().Println(err)
}
}

View File

@@ -0,0 +1,15 @@
package httpResponse
import (
"log"
"net/http"
)
func PlainTextHandler(w http.ResponseWriter, status int, text string) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(status)
_, err := w.Write([]byte(text))
if err != nil {
log.Default().Println(err)
}
}

View File

@@ -0,0 +1,9 @@
package httpResponse
import (
"net/http"
)
func SomethingWentWrong(w http.ResponseWriter) {
JSONHandler(w, http.StatusInternalServerError, `{"error": "Something went wrong"}`)
}

85
main.go
View File

@@ -1,12 +1,14 @@
package main package main
import ( import (
"context"
"database/sql" "database/sql"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/joho/godotenv" "github.com/joho/godotenv"
_ "github.com/lib/pq" _ "github.com/lib/pq"
"github.com/rdarius/go-http-server/internal/database" "github.com/rdarius/go-http-server/internal/database"
"github.com/rdarius/go-http-server/internal/httpResponse"
"log" "log"
"net/http" "net/http"
"os" "os"
@@ -17,6 +19,7 @@ import (
type apiConfig struct { type apiConfig struct {
fileserverHits atomic.Int32 fileserverHits atomic.Int32
db database.Queries db database.Queries
platform string
} }
func (cfg *apiConfig) middlewareMetricsInc(next http.Handler) http.Handler { func (cfg *apiConfig) middlewareMetricsInc(next http.Handler) http.Handler {
@@ -27,47 +30,42 @@ func (cfg *apiConfig) middlewareMetricsInc(next http.Handler) http.Handler {
} }
func readinessHandler(w http.ResponseWriter, r *http.Request) { func readinessHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8") httpResponse.PlainTextHandler(w, http.StatusOK, "OK")
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
} }
func metricsHandler(cfg *apiConfig) http.HandlerFunc { func metricsHandler(cfg *apiConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusOK)
hits := cfg.fileserverHits.Load() hits := cfg.fileserverHits.Load()
w.Write([]byte(fmt.Sprintf("Hits: %d", hits))) httpResponse.PlainTextHandler(w, http.StatusOK, fmt.Sprintf("Hits: %d", hits))
} }
} }
func adminMetricsHandler(cfg *apiConfig) http.HandlerFunc { func adminMetricsHandler(cfg *apiConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
hits := cfg.fileserverHits.Load() hits := cfg.fileserverHits.Load()
w.Write([]byte(fmt.Sprintf(`<html> httpResponse.HTMLHandler(w, http.StatusOK, fmt.Sprintf(`<html>
<body> <body>
<h1>Welcome, Chirpy Admin</h1> <h1>Welcome, Chirpy Admin</h1>
<p>Chirpy has been visited %d times!</p> <p>Chirpy has been visited %d times!</p>
</body> </body>
</html>`, hits))) </html>`, hits))
} }
} }
func resetMetricsHandler(cfg *apiConfig) http.HandlerFunc { func resetMetricsHandler(cfg *apiConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
cfg.fileserverHits.Store(0) if cfg.platform != "dev" {
w.WriteHeader(http.StatusOK) httpResponse.JSONHandler(w, http.StatusForbidden, `{"error": "Forbidden!"}`)
w.Write([]byte("Metrics Reset")) return
} }
err := cfg.db.DeleteAllUser(context.Background())
if err != nil {
httpResponse.SomethingWentWrong(w)
return
} }
func adminResetMetricsHandler(cfg *apiConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
cfg.fileserverHits.Store(0) cfg.fileserverHits.Store(0)
w.WriteHeader(http.StatusOK) httpResponse.PlainTextHandler(w, http.StatusOK, "Metrics Reset")
w.Write([]byte("Metrics Reset"))
} }
} }
@@ -76,6 +74,35 @@ func fileServerHandler() http.Handler {
return http.StripPrefix("/app", fileServer) return http.StripPrefix("/app", fileServer)
} }
func postUsersHandler(cfg *apiConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
type parameters struct {
Email string `json:"email"`
}
params := parameters{}
err := json.NewDecoder(r.Body).Decode(&params)
if err != nil {
httpResponse.JSONHandler(w, http.StatusBadRequest, `{"error": "Failed to parse request body"}`)
return
}
usr, err := cfg.db.CreateUser(context.Background(), params.Email)
if err != nil {
httpResponse.JSONHandler(w, http.StatusInternalServerError, fmt.Sprintf(`{"error": "Failed to create user", "message": "%s"}`, err.Error()))
return
}
jsonData := fmt.Sprintf(`{
"id": "%s",
"created_at": "%s",
"updated_at": "%s",
"email": "%s"
}`, usr.ID, usr.CreatedAt, usr.UpdatedAt, usr.Email)
httpResponse.JSONHandler(w, http.StatusCreated, jsonData)
}
}
func validateChirpHandler(w http.ResponseWriter, r *http.Request) { func validateChirpHandler(w http.ResponseWriter, r *http.Request) {
type parameters struct { type parameters struct {
Body string `json:"body"` Body string `json:"body"`
@@ -87,16 +114,12 @@ func validateChirpHandler(w http.ResponseWriter, r *http.Request) {
params := parameters{} params := parameters{}
err := decoder.Decode(&params) err := decoder.Decode(&params)
if err != nil { if err != nil {
w.Header().Set("Content-Type", "application/json; charset=utf-8") httpResponse.SomethingWentWrong(w)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(`{"error": "Something went wrong"}`))
return return
} }
if len(params.Body) > 140 { if len(params.Body) > 140 {
w.Header().Set("Content-Type", "application/json; charset=utf-8") httpResponse.JSONHandler(w, http.StatusBadRequest, `{"error": "Chirp is too long"}`)
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{"error": "Chirp is too long"}`))
return return
} }
@@ -108,9 +131,7 @@ func validateChirpHandler(w http.ResponseWriter, r *http.Request) {
chirp = re.ReplaceAllString(chirp, "****") chirp = re.ReplaceAllString(chirp, "****")
} }
w.Header().Set("Content-Type", "application/json; charset=utf-8") httpResponse.JSONHandler(w, http.StatusOK, fmt.Sprintf(`{"cleaned_body": "%s"}`, chirp))
w.WriteHeader(http.StatusOK)
w.Write([]byte(fmt.Sprintf(`{"cleaned_body": "%s"}`, chirp)))
return return
} }
@@ -119,16 +140,17 @@ func main() {
if err != nil { if err != nil {
log.Fatal("Error loading .env file") log.Fatal("Error loading .env file")
} }
apiCfg := &apiConfig{}
dbURL := os.Getenv("DB_URL") dbURL := os.Getenv("DB_URL")
apiCfg.platform = os.Getenv("PLATFORM")
db, err := sql.Open("postgres", dbURL) db, err := sql.Open("postgres", dbURL)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
apiCfg := &apiConfig{}
dbQueries := database.New(db) dbQueries := database.New(db)
apiCfg.db = *dbQueries apiCfg.db = *dbQueries
@@ -138,9 +160,10 @@ func main() {
mux.HandleFunc("GET /api/metrics", metricsHandler(apiCfg)) mux.HandleFunc("GET /api/metrics", metricsHandler(apiCfg))
mux.HandleFunc("POST /api/reset", resetMetricsHandler(apiCfg)) mux.HandleFunc("POST /api/reset", resetMetricsHandler(apiCfg))
mux.HandleFunc("POST /api/validate_chirp", validateChirpHandler) mux.HandleFunc("POST /api/validate_chirp", validateChirpHandler)
mux.HandleFunc("POST /api/users", postUsersHandler(apiCfg))
mux.HandleFunc("GET /admin/metrics", adminMetricsHandler(apiCfg)) mux.HandleFunc("GET /admin/metrics", adminMetricsHandler(apiCfg))
mux.HandleFunc("POST /admin/reset", adminResetMetricsHandler(apiCfg)) mux.HandleFunc("POST /admin/reset", resetMetricsHandler(apiCfg))
mux.Handle("/app/", apiCfg.middlewareMetricsInc(fileServerHandler())) mux.Handle("/app/", apiCfg.middlewareMetricsInc(fileServerHandler()))

View File

@@ -0,0 +1,2 @@
-- name: DeleteAllUser :exec
DELETE FROM users WHERE true;

View File

@@ -3,7 +3,7 @@ CREATE TABLE users(
id UUID PRIMARY KEY, id UUID PRIMARY KEY,
created_at TIMESTAMP not null DEFAULT CURRENT_TIMESTAMP, created_at TIMESTAMP not null DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP not null DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP not null DEFAULT CURRENT_TIMESTAMP,
email TEXT not null email TEXT not null UNIQUE
); );
-- +goose Down -- +goose Down