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