Skip to content
Snippets Groups Projects
Unverified Commit 277041d5 authored by Luca Moser's avatar Luca Moser Committed by GitHub
Browse files

use correct http codes for given responses (#189)

parent 5b4fd056
No related branches found
No related tags found
No related merge requests found
......@@ -29,6 +29,7 @@ var (
ErrNotFound = errors.New("not found")
ErrUnauthorized = errors.New("unauthorized")
ErrUnknownError = errors.New("unknown error")
ErrNotImplemented = errors.New("operation not implemented/supported/available")
)
const (
......@@ -87,6 +88,8 @@ func interpretBody(res *http.Response, decodeTo interface{}) error {
return fmt.Errorf("%w: %s", ErrBadRequest, errRes.Error)
case http.StatusUnauthorized:
return fmt.Errorf("%w: %s", ErrUnauthorized, errRes.Error)
case http.StatusNotImplemented:
return fmt.Errorf("%w: %s", ErrNotImplemented, errRes.Error)
}
return fmt.Errorf("%w: %s", ErrUnknownError, errRes.Error)
......
......@@ -33,7 +33,7 @@ func broadcastData(c echo.Context) error {
var request Request
if err := c.Bind(&request); err != nil {
log.Info(err.Error())
return requestFailed(c, err.Error())
return c.JSON(http.StatusBadRequest, Response{Error: err.Error()})
}
log.Debug("Received - address:", request.Address, " data:", request.Data)
......@@ -44,22 +44,22 @@ func broadcastData(c echo.Context) error {
buffer := make([]byte, 2187)
if len(request.Data) > 2187 {
log.Warn("Data exceeding 2187 byte limit -", len(request.Data))
return requestFailed(c, "Data exceeding 2187 byte limit")
log.Warnf("data exceeds 2187 byte limit - (payload data size: %d)", len(request.Data))
return c.JSON(http.StatusBadRequest, Response{Error: "data exceeds 2187 byte limit"})
}
copy(buffer, typeutils.StringToBytes(request.Data))
trytes, err := trinary.BytesToTrytes(buffer)
if err != nil {
log.Warn("Trytes conversion failed", err.Error())
return requestFailed(c, err.Error())
log.Warnf("trytes conversion failed: %s", err.Error())
return c.JSON(http.StatusBadRequest, Response{Error: err.Error()})
}
err = address.ValidAddress(request.Address)
if err != nil {
log.Warn("Invalid Address:", request.Address)
return requestFailed(c, err.Error())
log.Warnf("invalid Address: %s", request.Address)
return c.JSON(http.StatusBadRequest, Response{Error: err.Error()})
}
tx.SetAddress(request.Address)
......@@ -69,24 +69,12 @@ func broadcastData(c echo.Context) error {
tx.SetTrunkTransactionHash(tipselection.GetRandomTip())
tx.SetTimestamp(uint(time.Now().Unix()))
if err := tx.DoProofOfWork(meta_transaction.MIN_WEIGHT_MAGNITUDE); err != nil {
log.Warn("PoW failed", err)
return requestFailed(c, err.Error())
log.Warnf("PoW failed: %s", err)
return c.JSON(http.StatusInternalServerError, Response{Error: err.Error()})
}
gossip.Events.TransactionReceived.Trigger(&gossip.TransactionReceivedEvent{Data: tx.GetBytes(), Peer: &local.GetInstance().Peer})
return requestSuccessful(c, tx.GetHash())
}
func requestSuccessful(c echo.Context, txHash string) error {
return c.JSON(http.StatusCreated, Response{
Hash: txHash,
})
}
func requestFailed(c echo.Context, message string) error {
return c.JSON(http.StatusBadRequest, Response{
Error: message,
})
return c.JSON(http.StatusOK, Response{Hash: tx.GetHash()})
}
type Response struct {
......
......@@ -28,7 +28,7 @@ func findTransactionHashes(c echo.Context) error {
if err := c.Bind(&request); err != nil {
log.Info(err.Error())
return requestFailed(c, err.Error())
return c.JSON(http.StatusBadRequest, Response{Error: err.Error()})
}
log.Debug("Received:", request.Addresses)
result := make([][]trinary.Trytes, len(request.Addresses))
......@@ -36,24 +36,12 @@ func findTransactionHashes(c echo.Context) error {
for i, address := range request.Addresses {
txs, err := tangle.ReadTransactionHashesForAddressFromDatabase(address)
if err != nil {
return requestFailed(c, err.Error())
return c.JSON(http.StatusInternalServerError, Response{Error: err.Error()})
}
result[i] = append(result[i], txs...)
}
return requestSuccessful(c, result)
}
func requestSuccessful(c echo.Context, txHashes [][]trinary.Trytes) error {
return c.JSON(http.StatusOK, Response{
Transactions: txHashes,
})
}
func requestFailed(c echo.Context, message string) error {
return c.JSON(http.StatusNotFound, Response{
Error: message,
})
return c.JSON(http.StatusOK, Response{Transactions: result})
}
type Response struct {
......
......@@ -26,11 +26,11 @@ func getNeighbors(c echo.Context) error {
knownPeers := []Neighbor{}
if autopeering.Selection == nil {
return requestFailed(c, "Neighbor Selection is not enabled")
return c.JSON(http.StatusNotImplemented, Response{Error: "Neighbor Selection is not enabled"})
}
if autopeering.Discovery == nil {
return requestFailed(c, "Neighbor Discovery is not enabled")
return c.JSON(http.StatusNotImplemented, Response{Error: "Neighbor Discovery is not enabled"})
}
if c.QueryParam("known") == "1" {
......@@ -45,7 +45,6 @@ func getNeighbors(c echo.Context) error {
}
for _, peer := range autopeering.Selection.GetOutgoingNeighbors() {
n := Neighbor{
ID: peer.ID().String(),
PublicKey: base64.StdEncoding.EncodeToString(peer.PublicKey()),
......@@ -62,21 +61,7 @@ func getNeighbors(c echo.Context) error {
accepted = append(accepted, n)
}
return requestSuccessful(c, knownPeers, chosen, accepted)
}
func requestSuccessful(c echo.Context, knownPeers, chosen, accepted []Neighbor) error {
return c.JSON(http.StatusOK, Response{
KnownPeers: knownPeers,
Chosen: chosen,
Accepted: accepted,
})
}
func requestFailed(c echo.Context, message string) error {
return c.JSON(http.StatusNotFound, Response{
Error: message,
})
return c.JSON(http.StatusOK, Response{KnownPeers: knownPeers, Chosen: chosen, Accepted: accepted})
}
type Response struct {
......
package getTransactionObjectsByHash
import (
"fmt"
"net/http"
"github.com/iotaledger/goshimmer/plugins/tangle"
......@@ -30,7 +31,7 @@ func getTransactionObjectsByHash(c echo.Context) error {
if err := c.Bind(&request); err != nil {
log.Info(err.Error())
return requestFailed(c, err.Error())
return c.JSON(http.StatusBadRequest, Response{Error: err.Error()})
}
log.Debug("Received:", request.Hashes)
......@@ -38,43 +39,28 @@ func getTransactionObjectsByHash(c echo.Context) error {
for _, hash := range request.Hashes {
tx, err := tangle.GetTransaction(hash)
if err != nil {
return requestFailed(c, err.Error())
return c.JSON(http.StatusInternalServerError, Response{Error: err.Error()})
}
if tx != nil {
t := Transaction{
Hash: tx.GetHash(),
WeightMagnitude: tx.GetWeightMagnitude(),
TrunkTransactionHash: tx.GetTrunkTransactionHash(),
BranchTransactionHash: tx.GetBranchTransactionHash(),
Head: tx.IsHead(),
Tail: tx.IsTail(),
Nonce: tx.GetNonce(),
Address: tx.GetAddress(),
Value: tx.GetValue(),
Timestamp: tx.GetTimestamp(),
SignatureMessageFragment: tx.GetSignatureMessageFragment(),
}
result = append(result, t)
} else {
//tx not found
result = append(result, Transaction{})
if tx == nil {
return c.JSON(http.StatusNotFound, Response{Error: fmt.Sprintf("transaction not found: %s", hash)})
}
t := Transaction{
Hash: tx.GetHash(),
WeightMagnitude: tx.GetWeightMagnitude(),
TrunkTransactionHash: tx.GetTrunkTransactionHash(),
BranchTransactionHash: tx.GetBranchTransactionHash(),
Head: tx.IsHead(),
Tail: tx.IsTail(),
Nonce: tx.GetNonce(),
Address: tx.GetAddress(),
Value: tx.GetValue(),
Timestamp: tx.GetTimestamp(),
SignatureMessageFragment: tx.GetSignatureMessageFragment(),
}
result = append(result, t)
}
return requestSuccessful(c, result)
}
func requestSuccessful(c echo.Context, txs []Transaction) error {
return c.JSON(http.StatusOK, Response{
Transactions: txs,
})
}
func requestFailed(c echo.Context, message string) error {
return c.JSON(http.StatusNotFound, Response{
Error: message,
})
return c.JSON(http.StatusOK, Response{Transactions: result})
}
type Response struct {
......
package getTransactionTrytesByHash
import (
"fmt"
"net/http"
"github.com/iotaledger/goshimmer/plugins/tangle"
......@@ -29,38 +30,23 @@ func getTransactionTrytesByHash(c echo.Context) error {
result := []trinary.Trytes{}
if err := c.Bind(&request); err != nil {
log.Info(err.Error())
return requestFailed(c, err.Error())
return c.JSON(http.StatusBadRequest, Response{Error: err.Error()})
}
log.Debug("Received:", request.Hashes)
for _, hash := range request.Hashes {
tx, err := tangle.GetTransaction(hash)
if err != nil {
return requestFailed(c, err.Error())
return c.JSON(http.StatusInternalServerError, Response{Error: err.Error()})
}
if tx != nil {
trytes := trinary.MustTritsToTrytes(tx.GetTrits())
result = append(result, trytes)
} else {
//tx not found
result = append(result, "")
if tx == nil {
return c.JSON(http.StatusNotFound, Response{Error: fmt.Sprintf("transaction not found: %s", hash)})
}
trytes := trinary.MustTritsToTrytes(tx.GetTrits())
result = append(result, trytes)
}
return requestSuccessful(c, result)
}
func requestSuccessful(c echo.Context, txTrytes []trinary.Trytes) error {
return c.JSON(http.StatusOK, Response{
Trytes: txTrytes,
})
}
func requestFailed(c echo.Context, message string) error {
return c.JSON(http.StatusNotFound, Response{
Error: message,
})
return c.JSON(http.StatusOK, Response{Trytes: result})
}
type Response struct {
......
......@@ -19,7 +19,7 @@ func WebApiHandler(c echo.Context) error {
var request Request
if err := c.Bind(&request); err != nil {
return requestFailed(c, err.Error())
return c.JSON(http.StatusBadRequest, Response{Error: err.Error()})
}
switch request.Cmd {
......@@ -30,33 +30,18 @@ func WebApiHandler(c echo.Context) error {
transactionspammer.Stop()
transactionspammer.Start(request.Tps)
return requestSuccessful(c, "started spamming transactions")
return c.JSON(http.StatusOK, Response{Message: "started spamming transactions"})
case "stop":
transactionspammer.Stop()
return requestSuccessful(c, "stopped spamming transactions")
return c.JSON(http.StatusOK, Response{Message: "stopped spamming transactions"})
default:
return requestFailed(c, "invalid cmd in request")
return c.JSON(http.StatusBadRequest, Response{Error: "invalid cmd in request"})
}
}
func requestSuccessful(c echo.Context, message string) error {
return c.JSON(http.StatusOK, Response{
Message: message,
})
}
func requestFailed(c echo.Context, message string) error {
return c.JSON(http.StatusNotFound, Response{
Message: message,
})
}
type Response struct {
Message string `json:"message"`
Error string `json:"error"`
}
type Request struct {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment