Getting the paymentIntent set up route and handler in API

This commit is contained in:
2024-08-04 16:26:02 +02:00
parent 79215d5fe1
commit 41cd4cc055
6 changed files with 246 additions and 1 deletions

89
cmd/api/api.go Normal file
View File

@ -0,0 +1,89 @@
package main
import (
"flag"
"fmt"
"log"
"net/http"
"os"
"time"
)
const (
version = "1.0.0"
)
type config struct {
port int
env string
db struct {
dsn string
}
stripe struct {
secret string
key string
}
}
type application struct {
config config
infolog *log.Logger
errorLog *log.Logger
version string
}
func (app *application) serve() error {
srv := &http.Server{
Addr: fmt.Sprintf(":%d", app.config.port),
Handler: app.routes(),
IdleTimeout: 30 * time.Second,
ReadTimeout: 10 * time.Second,
ReadHeaderTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
}
app.infolog.Printf(
"Starting Backend server in %s mode on port %d",
app.config.env,
app.config.port,
)
return srv.ListenAndServe()
}
func main() {
var cfg config
flag.IntVar(&cfg.port, "port", 4001, "Server port to listen on")
flag.StringVar(
&cfg.env,
"env",
"development",
"Application environment {development|production|maintenance}",
)
flag.StringVar(
&cfg.db.dsn,
"dsn",
"root@tcp(localhost:6379)/widgets?parseTime=true&tls=false",
"Application environment {development|production}",
)
flag.Parse()
cfg.stripe.key = os.Getenv("STRIPE_KEY")
cfg.stripe.secret = os.Getenv("STRIPE_SECRET")
infoLog := log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime)
errorLog := log.New(os.Stdout, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile)
app := &application{
version: version,
config: cfg,
infolog: infoLog,
errorLog: errorLog,
}
err := app.serve()
if err != nil {
log.Fatal(err)
}
}

32
cmd/api/handlers-api.go Normal file
View File

@ -0,0 +1,32 @@
package main
import (
"encoding/json"
"net/http"
)
type stripePayload struct {
Currency string `json:"currency"`
Amount string `json:"amount"`
}
type jsonResponse struct {
OK bool `json:"ok"`
Message string `json:"message"`
Content string `json:"content"`
ID int `json:"id"`
}
func (app *application) GetPaymentIntent(w http.ResponseWriter, r *http.Request) {
j := jsonResponse{
OK: true,
}
out, err := json.MarshalIndent(j, "", " ")
if err != nil {
app.errorLog.Println(err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(out)
}

23
cmd/api/routes-api.go Normal file
View File

@ -0,0 +1,23 @@
package main
import (
"net/http"
"github.com/go-chi/chi/v5"
"github.com/go-chi/cors"
)
func (app *application) routes() http.Handler {
mux := chi.NewRouter()
mux.Use(cors.Handler(cors.Options{
AllowedOrigins: []string{"https://*", "http://*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
AllowCredentials: false,
MaxAge: 300,
}))
mux.Get("/api/payment-intent", app.GetPaymentIntent)
return mux
}