commit 21a54daf045c25b16dc838963f52e7f420b0eb13
parent 8a5078922e0cf7468fc1d7a614e80b6903a94721
Author: Shivakumar <[email protected]>
Date: Mon, 10 Aug 2026 21:24:39 +0530
feat(respond): add Error and JSON method
- fix all the handlers with respond subsitution
Signed-off-by: Shivakumar <[email protected]>
Diffstat:
5 files changed, 78 insertions(+), 53 deletions(-)
diff --git a/api/handlers/blocks.go b/api/handlers/blocks.go
@@ -22,6 +22,7 @@ import (
"time"
"certichain/api/dto"
+ "certichain/api/respond"
"certichain/internal/blockchain"
"certichain/internal/storage"
)
@@ -32,7 +33,7 @@ func GetBlock(bc *blockchain.Blockchain) http.HandlerFunc {
blockHash := r.PathValue("hash")
hash, err := hex.DecodeString(blockHash)
if err != nil {
- writeError(w, http.StatusBadRequest, "invalid_body", "invalid hex encoding")
+ respond.Error(w, http.StatusBadRequest, "invalid_body", "invalid hex encoding")
return
}
@@ -52,7 +53,7 @@ func GetBlockByHeight(bc *blockchain.Blockchain) http.HandlerFunc {
height, err := strconv.ParseUint(blockHeight, 10, 64)
if err != nil {
- writeError(w, http.StatusBadRequest, "invalid_body", "invalid height: must be non-negative integer")
+ respond.Error(w, http.StatusBadRequest, "invalid_body", "invalid height: must be non-negative integer")
return
}
@@ -95,7 +96,7 @@ func writeBlock(w http.ResponseWriter, block *blockchain.Block) {
})
}
- writeJSON(w, http.StatusOK, dto.BlockResponse{
+ respond.JSON(w, http.StatusOK, dto.BlockResponse{
Height: block.Header.Height,
Hash: block.Hash.String(),
PrevHash: block.Header.PrevHash.String(),
@@ -109,8 +110,8 @@ func writeBlock(w http.ResponseWriter, block *blockchain.Block) {
// writeStorageError checks for 404 or 500 error status code.
func writeStorageError(w http.ResponseWriter, err error, msg string) {
if errors.Is(err, storage.ErrNotFound) {
- writeError(w, http.StatusNotFound, "not_found", msg)
+ respond.Error(w, http.StatusNotFound, "not_found", msg)
return
}
- writeError(w, http.StatusInternalServerError, "server_error", "internal server error")
+ respond.Error(w, http.StatusInternalServerError, "server_error", "internal server error")
}
diff --git a/api/handlers/institution.go b/api/handlers/institution.go
@@ -21,36 +21,23 @@ import (
"net/http"
"certichain/api/dto"
+ "certichain/api/respond"
"certichain/internal/registry"
"certichain/internal/storage"
)
-// writeJSON writes v as a JSON response with the given status code.
-func writeJSON(w http.ResponseWriter, status int, v any) {
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(status)
- json.NewEncoder(w).Encode(v)
-}
-
-// writeError writes a dto.ErrorResponse with the given status, code, and message.
-func writeError(w http.ResponseWriter, status int, code, message string) {
- writeJSON(w, status, dto.ErrorResponse{
- Error: dto.ErrorDetail{Code: code, Message: message},
- })
-}
-
// RegisterInstitution returns a handler for POST /v1/institutions.
func RegisterInstitution(reg *registry.Registry) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req dto.RegisterInstitutionRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- writeError(w, http.StatusBadRequest, "invalid_body", "malformed JSON body")
+ respond.Error(w, http.StatusBadRequest, "invalid_body", "malformed JSON body")
return
}
pubKey, err := hex.DecodeString(req.PublicKey)
if err != nil {
- writeError(w, http.StatusBadRequest, "invalid_body", "Invalid Hex Encoding")
+ respond.Error(w, http.StatusBadRequest, "invalid_body", "Invalid Hex Encoding")
return
}
@@ -58,16 +45,16 @@ func RegisterInstitution(reg *registry.Registry) http.HandlerFunc {
if err != nil {
switch {
case errors.Is(err, registry.ErrInvalidKey):
- writeError(w, http.StatusBadRequest, "invalid_body", "Invalid Public Key")
+ respond.Error(w, http.StatusBadRequest, "invalid_body", "Invalid Public Key")
case errors.Is(err, registry.ErrAlreadyExists):
- writeError(w, http.StatusConflict, "already_exists", "Public Key already exists")
+ respond.Error(w, http.StatusConflict, "already_exists", "Public Key already exists")
default:
- writeError(w, http.StatusInternalServerError, "server_error", "Internal Server Error")
+ respond.Error(w, http.StatusInternalServerError, "server_error", "Internal Server Error")
}
return
}
- writeJSON(w, http.StatusCreated, dto.RegisterInstitutionResponse{DID: did})
+ respond.JSON(w, http.StatusCreated, dto.RegisterInstitutionResponse{DID: did})
}
}
@@ -79,22 +66,22 @@ func GetInstitution(reg *registry.Registry) http.HandlerFunc {
_, err := reg.Get(did)
switch {
case err == nil:
- writeJSON(w, http.StatusOK, &dto.GetInstitutionResponse{
+ respond.JSON(w, http.StatusOK, &dto.GetInstitutionResponse{
DID: did,
Registered: true,
})
return
case errors.Is(err, storage.ErrNotFound):
- writeJSON(w, http.StatusOK, &dto.GetInstitutionResponse{
+ respond.JSON(w, http.StatusOK, &dto.GetInstitutionResponse{
DID: "",
Registered: false,
})
return
case errors.Is(err, registry.ErrInvalidDID):
- writeError(w, http.StatusBadRequest, "invalid_did", "malformed DID")
+ respond.Error(w, http.StatusBadRequest, "invalid_did", "malformed DID")
return
default:
- writeError(w, http.StatusInternalServerError, "server_error", "Internal Server Error")
+ respond.Error(w, http.StatusInternalServerError, "server_error", "Internal Server Error")
return
}
}
diff --git a/api/handlers/transactions.go b/api/handlers/transactions.go
@@ -22,6 +22,7 @@ import (
"time"
"certichain/api/dto"
+ "certichain/api/respond"
"certichain/internal/blockchain"
"certichain/internal/mempool"
"certichain/internal/registry"
@@ -34,28 +35,28 @@ func SubmitTransaction(mem *mempool.Mempool, reg *registry.Registry) http.Handle
return func(w http.ResponseWriter, r *http.Request) {
var req dto.SubmitTransactionRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- writeError(w, http.StatusBadRequest, "invalid_body", "malformed JSON body")
+ respond.Error(w, http.StatusBadRequest, "invalid_body", "malformed JSON body")
return
}
txID, err := hex.DecodeString(req.TxID)
if err != nil {
- writeError(w, http.StatusBadRequest, "invalid_body", "invalid TxID hex encoding")
+ respond.Error(w, http.StatusBadRequest, "invalid_body", "invalid TxID hex encoding")
return
}
nonce, err := hex.DecodeString(req.Nonce)
if err != nil {
- writeError(w, http.StatusBadRequest, "invalid_body", "invalid nonce hex encoding")
+ respond.Error(w, http.StatusBadRequest, "invalid_body", "invalid nonce hex encoding")
return
}
merkleRoot, err := hex.DecodeString(req.MerkleRoot)
if err != nil {
- writeError(w, http.StatusBadRequest, "invalid_body", "invalid merkleroot hex encoding")
+ respond.Error(w, http.StatusBadRequest, "invalid_body", "invalid merkleroot hex encoding")
return
}
signature, err := hex.DecodeString(req.Signature)
if err != nil {
- writeError(w, http.StatusBadRequest, "invalid_body", "invalid signature hex encoding")
+ respond.Error(w, http.StatusBadRequest, "invalid_body", "invalid signature hex encoding")
return
}
@@ -72,40 +73,40 @@ func SubmitTransaction(mem *mempool.Mempool, reg *registry.Registry) http.Handle
if err != nil {
switch {
case errors.Is(err, storage.ErrNotFound):
- writeError(w, http.StatusBadRequest, "unknown_issuer", "issuer DID is not registered")
+ respond.Error(w, http.StatusBadRequest, "unknown_issuer", "issuer DID is not registered")
return
case errors.Is(err, registry.ErrInvalidDID):
- writeError(w, http.StatusBadRequest, "invalid_body", "malformed issuer DID")
+ respond.Error(w, http.StatusBadRequest, "invalid_body", "malformed issuer DID")
return
default:
- writeError(w, http.StatusInternalServerError, "server_error", "internal server error")
+ respond.Error(w, http.StatusInternalServerError, "server_error", "internal server error")
return
}
}
valid, err := tx.Verify(pubKey)
if err != nil {
- writeError(w, http.StatusBadRequest, "invalid_body", err.Error())
+ respond.Error(w, http.StatusBadRequest, "invalid_body", err.Error())
return
}
if !valid {
- writeError(w, http.StatusForbidden, "invalid_signature", "signature verification failed")
+ respond.Error(w, http.StatusForbidden, "invalid_signature", "signature verification failed")
return
}
if err := mem.Add(tx); err != nil {
switch {
case errors.Is(err, mempool.ErrDuplicateTx):
- writeError(w, http.StatusConflict, "duplicate_transaction", "transaction already submitted")
+ respond.Error(w, http.StatusConflict, "duplicate_transaction", "transaction already submitted")
case errors.Is(err, mempool.ErrMempoolFull):
- writeError(w, http.StatusServiceUnavailable, "mempool_full", "mempool is at capacity, try again later")
+ respond.Error(w, http.StatusServiceUnavailable, "mempool_full", "mempool is at capacity, try again later")
default:
- writeError(w, http.StatusInternalServerError, "server_error", "internal server error")
+ respond.Error(w, http.StatusInternalServerError, "server_error", "internal server error")
}
return
}
- writeJSON(w, http.StatusCreated, dto.SubmitTransactionResponse{TxID: req.TxID, Status: "pending"})
+ respond.JSON(w, http.StatusCreated, dto.SubmitTransactionResponse{TxID: req.TxID, Status: "pending"})
}
}
@@ -116,12 +117,12 @@ func GetTransaction(mem *mempool.Mempool, bc *blockchain.Blockchain) http.Handle
txID, err := hex.DecodeString(txIDHex)
if err != nil {
- writeError(w, http.StatusBadRequest, "invalid_body", "invalid tx_id hex encoding")
+ respond.Error(w, http.StatusBadRequest, "invalid_body", "invalid tx_id hex encoding")
return
}
if tx := mem.Get(txID); tx != nil {
- writeJSON(w, http.StatusOK, &dto.GetTransactionResponse{
+ respond.JSON(w, http.StatusOK, &dto.GetTransactionResponse{
TxID: txIDHex,
IssuerDID: tx.IssuerDID,
MerkleRoot: hex.EncodeToString(tx.MerkleRoot),
@@ -134,22 +135,22 @@ func GetTransaction(mem *mempool.Mempool, bc *blockchain.Blockchain) http.Handle
tx, err := bc.GetTransaction(txID)
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
- writeError(w, http.StatusNotFound, "not_found", "transaction not found")
+ respond.Error(w, http.StatusNotFound, "not_found", "transaction not found")
return
}
- writeError(w, http.StatusInternalServerError, "server_error", "internal server error")
+ respond.Error(w, http.StatusInternalServerError, "server_error", "internal server error")
return
}
block, err := bc.GetBlockByTxID(txID)
if err != nil {
- writeError(w, http.StatusInternalServerError, "server_error", "internal server error")
+ respond.Error(w, http.StatusInternalServerError, "server_error", "internal server error")
return
}
blockHash := hex.EncodeToString(block.Hash[:])
- writeJSON(w, http.StatusOK, &dto.GetTransactionResponse{
+ respond.JSON(w, http.StatusOK, &dto.GetTransactionResponse{
TxID: txIDHex,
IssuerDID: tx.IssuerDID,
MerkleRoot: hex.EncodeToString(tx.MerkleRoot),
diff --git a/api/handlers/verify.go b/api/handlers/verify.go
@@ -20,6 +20,7 @@ import (
"time"
"certichain/api/dto"
+ "certichain/api/respond"
"certichain/internal/blockchain"
"certichain/internal/registry"
)
@@ -31,7 +32,7 @@ func Verify(bc *blockchain.Blockchain, reg *registry.Registry) http.HandlerFunc
txID, err := hex.DecodeString(txIDhash)
if err != nil {
- writeError(w, http.StatusBadRequest, "invalid_body", "invalid hex encoding")
+ respond.Error(w, http.StatusBadRequest, "invalid_body", "invalid hex encoding")
return
}
@@ -54,16 +55,16 @@ func Verify(bc *blockchain.Blockchain, reg *registry.Registry) http.HandlerFunc
ok, err := tx.Verify(pubKey)
if err != nil {
- writeError(w, http.StatusInternalServerError, "server_error", "internal server error")
+ respond.Error(w, http.StatusInternalServerError, "server_error", "internal server error")
return
}
if !ok {
- writeError(w, http.StatusUnauthorized, "invalid_signature", "signature verification failed")
+ respond.Error(w, http.StatusUnauthorized, "invalid_signature", "signature verification failed")
return
}
- writeJSON(w, http.StatusOK, &dto.VerifyResponse{
+ respond.JSON(w, http.StatusOK, &dto.VerifyResponse{
TxID: hex.EncodeToString(tx.TxID),
IssuerDID: tx.IssuerDID,
IssuerPublicKey: hex.EncodeToString(pubKey),
diff --git a/api/respond/respond.go b/api/respond/respond.go
@@ -0,0 +1,35 @@
+// Copyright 2026 Shivakumar (Certichain)
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package respond
+
+import (
+ "certichain/api/dto"
+ "encoding/json"
+ "net/http"
+)
+
+// JSON writes v as a JSON response with the given status code.
+func JSON(w http.ResponseWriter, status int, v any) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ json.NewEncoder(w).Encode(v)
+}
+
+// Error writes a dto.ErrorRespose with the given status, code and message.
+func Error(w http.ResponseWriter, status int, code, message string) {
+ JSON(w, status, dto.ErrorResponse{
+ Error: dto.ErrorDetail{Code: code, Message: message},
+ })
+}