VerifactuMidAPI/api/handler.go

59 lines
1.3 KiB
Go
Raw Normal View History

package api
import (
"encoding/base64"
"fmt"
"io"
"net/http"
"VerifactuMidAPI/internal/cert"
"VerifactuMidAPI/internal/config"
"VerifactuMidAPI/internal/crypto"
)
type Handler struct {
cfg *config.Config
cert *cert.Storage
crypto *crypto.KeyPair
}
func New(cfg *config.Config, certStorage *cert.Storage, keyPair *crypto.KeyPair) *Handler {
return &Handler{
cfg: cfg,
cert: certStorage,
crypto: keyPair,
}
}
func (h *Handler) GetPublicKey(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
pubPEM, err := h.crypto.PublicKeyPEM()
if err != nil {
http.Error(w, "failed to get public key", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(fmt.Sprintf(`{"public_key":"%s"}`, base64.StdEncoding.EncodeToString(pubPEM))))
}
func (h *Handler) RegisterCert(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "failed to read body", http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(body)
}