micw/server/api/http/transaction.go

69 lines
1.6 KiB
Go
Raw Normal View History

2024-11-13 21:10:13 +00:00
package http
import (
"context"
"encoding/json"
2024-11-24 14:04:52 +00:00
"errors"
"github.com/matchsystems/werr"
"log"
"mic-wallet/common"
"mic-wallet/server/core"
2024-11-13 21:10:13 +00:00
logicErr "mic-wallet/server/logic/err"
"net/http"
)
2024-11-24 14:04:52 +00:00
func NewTransaction(ctx context.Context, w http.ResponseWriter, r *http.Request, d ApiDependencies) {
defer func() {
if err := r.Body.Close(); err != nil {
log.Printf("error closing request body: %s", err.Error())
}
}()
req := &common.NewTxOpts{}
2024-11-13 21:10:13 +00:00
if err := json.NewDecoder(r.Body).Decode(req); err != nil {
2024-11-24 14:04:52 +00:00
http.Error(w, "invalid request body", http.StatusBadRequest)
return
2024-11-13 21:10:13 +00:00
}
2024-11-24 14:04:52 +00:00
if err := d.WriteTx(req); err != nil {
if errors.Is(werr.UnwrapAll(err), core.ErrTxDuplicate) {
http.Error(w, "transaction already exists", http.StatusConflict)
return
}
w.WriteHeader(http.StatusInternalServerError)
2024-11-13 21:10:13 +00:00
}
2024-11-24 14:04:52 +00:00
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
2024-11-13 21:10:13 +00:00
}
func GetTransaction(w http.ResponseWriter, r *http.Request) *logicErr.Err {
return nil
}
func GetTransactions(w http.ResponseWriter, r *http.Request) *logicErr.Err {
txHash := r.URL.Query().Get("tx_sh")
if txHash != "" {
return nil
}
pubKey := r.URL.Query().Get("pub_key")
if pubKey != "" {
return nil
}
return nil
}
func MountTransactionRoutes(ctx context.Context, mux *http.ServeMux, thisRoute string) {
thisRoute += "/transaction"
mux.HandleFunc(thisRoute, func(w http.ResponseWriter, r *http.Request) {
var err *logicErr.Err
switch r.Method {
case http.MethodGet:
err = GetTransactions(w, r)
case http.MethodPost:
err = NewTransaction(w, r)
}
logicErr.HandleHttp(ctx, w, r, err)
})
}