package service import ( "Portifolio/internal/model" "database/sql" "encoding/json" "net/http" _ "github.com/mattn/go-sqlite3" ) type Service struct { db *sql.DB } func (s *Service) AddCurrencyHandler() http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var input model.CurrencyInput if err := json.NewDecoder(r.Body).Decode(&input); err != nil { http.Error(w, "invalid json", http.StatusBadRequest) return } id, err := s.InsertCurrency(input) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(map[string]any{"status": "created", "id": id}) } } func (s *Service) GetCurrenciesHandler() http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { currencies, err := s.GetAllCurrencies() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(currencies) } } func (s *Service) InsertCurrency(input model.CurrencyInput) (int, error) { res, err := s.db.Exec( `INSERT INTO currencies (code, name) VALUES (?, ?)`, input.Code, input.Name, ) if err != nil { return 0, err } id, err := res.LastInsertId() return int(id), err } func (s *Service) GetCurrencyByCode(code string) (*model.Currency, error) { c := &model.Currency{} err := s.db.QueryRow( `SELECT id, code, name FROM currencies WHERE code = ?`, code, ).Scan(&c.ID, &c.Code, &c.Name) if err == sql.ErrNoRows { return nil, nil } return c, err } func (s *Service) GetAllCurrencies() ([]model.Currency, error) { rows, err := s.db.Query(`SELECT id, code, name FROM currencies ORDER BY code`) if err != nil { return nil, err } defer rows.Close() var currencies []model.Currency for rows.Next() { var c model.Currency if err := rows.Scan(&c.ID, &c.Code, &c.Name); err != nil { return nil, err } currencies = append(currencies, c) } return currencies, rows.Err() }