first commit
This commit is contained in:
No files matched your search
@@ -0,0 +1,169 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"api-service/internal/config"
|
||||
models "api-service/internal/models/auth"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// AuthService handles authentication logic
|
||||
type AuthService struct {
|
||||
config *config.Config
|
||||
users map[string]*models.User // In-memory user store for demo
|
||||
}
|
||||
|
||||
// NewAuthService creates a new authentication service
|
||||
func NewAuthService(cfg *config.Config) *AuthService {
|
||||
// Initialize with demo users
|
||||
users := make(map[string]*models.User)
|
||||
|
||||
// Add demo users
|
||||
users["admin"] = &models.User{
|
||||
ID: "1",
|
||||
Username: "admin",
|
||||
Email: "[email protected]",
|
||||
Password: "$2a$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi", // password
|
||||
Role: "admin",
|
||||
}
|
||||
|
||||
users["user"] = &models.User{
|
||||
ID: "2",
|
||||
Username: "user",
|
||||
Email: "[email protected]",
|
||||
Password: "$2a$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi", // password
|
||||
Role: "user",
|
||||
}
|
||||
|
||||
return &AuthService{
|
||||
config: cfg,
|
||||
users: users,
|
||||
}
|
||||
}
|
||||
|
||||
// Login authenticates user and generates JWT token
|
||||
func (s *AuthService) Login(username, password string) (*models.TokenResponse, error) {
|
||||
user, exists := s.users[username]
|
||||
if !exists {
|
||||
return nil, errors.New("invalid credentials")
|
||||
}
|
||||
|
||||
// Verify password
|
||||
err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid credentials")
|
||||
}
|
||||
|
||||
// Generate JWT token
|
||||
token, err := s.generateToken(user)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &models.TokenResponse{
|
||||
AccessToken: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresIn: 3600, // 1 hour
|
||||
}, nil
|
||||
}
|
||||
|
||||
// generateToken creates a new JWT token for the user
|
||||
func (s *AuthService) generateToken(user *models.User) (string, error) {
|
||||
// Create claims
|
||||
claims := jwt.MapClaims{
|
||||
"user_id": user.ID,
|
||||
"username": user.Username,
|
||||
"email": user.Email,
|
||||
"role": user.Role,
|
||||
"exp": time.Now().Add(time.Hour * 1).Unix(),
|
||||
"iat": time.Now().Unix(),
|
||||
}
|
||||
|
||||
// Create token
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
|
||||
// Sign token with secret key
|
||||
secretKey := []byte(s.getJWTSecret())
|
||||
return token.SignedString(secretKey)
|
||||
}
|
||||
|
||||
// GenerateTokenForUser generates a JWT token for a specific user
|
||||
func (s *AuthService) GenerateTokenForUser(user *models.User) (string, error) {
|
||||
// Create claims
|
||||
claims := jwt.MapClaims{
|
||||
"user_id": user.ID,
|
||||
"username": user.Username,
|
||||
"email": user.Email,
|
||||
"role": user.Role,
|
||||
"exp": time.Now().Add(time.Hour * 1).Unix(),
|
||||
"iat": time.Now().Unix(),
|
||||
}
|
||||
|
||||
// Create token
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
|
||||
// Sign token with secret key
|
||||
secretKey := []byte(s.getJWTSecret())
|
||||
return token.SignedString(secretKey)
|
||||
}
|
||||
|
||||
// ValidateToken validates the JWT token
|
||||
func (s *AuthService) ValidateToken(tokenString string) (*models.JWTClaims, error) {
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, errors.New("unexpected signing method")
|
||||
}
|
||||
return []byte(s.getJWTSecret()), nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !token.Valid {
|
||||
return nil, errors.New("invalid token")
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
if !ok {
|
||||
return nil, errors.New("invalid claims")
|
||||
}
|
||||
|
||||
return &models.JWTClaims{
|
||||
UserID: claims["user_id"].(string),
|
||||
Username: claims["username"].(string),
|
||||
Email: claims["email"].(string),
|
||||
Role: claims["role"].(string),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// getJWTSecret returns the JWT secret key
|
||||
func (s *AuthService) getJWTSecret() string {
|
||||
// In production, this should come from environment variables
|
||||
return "your-secret-key-change-this-in-production"
|
||||
}
|
||||
|
||||
// RegisterUser registers a new user (for demo purposes)
|
||||
func (s *AuthService) RegisterUser(username, email, password, role string) error {
|
||||
if _, exists := s.users[username]; exists {
|
||||
return errors.New("username already exists")
|
||||
}
|
||||
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
s.users[username] = &models.User{
|
||||
ID: string(rune(len(s.users) + 1)),
|
||||
Username: username,
|
||||
Email: email,
|
||||
Password: string(hashedPassword),
|
||||
Role: role,
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
@@ -0,0 +1,564 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"api-service/internal/config"
|
||||
"api-service/internal/models/vclaim/peserta"
|
||||
|
||||
"github.com/mashingan/smapping"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// VClaimService interface for VClaim operations
|
||||
type VClaimService interface {
|
||||
Get(ctx context.Context, endpoint string, result interface{}) error
|
||||
Post(ctx context.Context, endpoint string, payload interface{}, result interface{}) error
|
||||
Put(ctx context.Context, endpoint string, payload interface{}, result interface{}) error
|
||||
Patch(ctx context.Context, endpoint string, payload interface{}, result interface{}) error
|
||||
Delete(ctx context.Context, endpoint string, result interface{}) error
|
||||
GetRawResponse(ctx context.Context, endpoint string) (*ResponDTOVclaim, error)
|
||||
PostRawResponse(ctx context.Context, endpoint string, payload interface{}) (*ResponDTOVclaim, error)
|
||||
PutRawResponse(ctx context.Context, endpoint string, payload interface{}) (*ResponDTOVclaim, error)
|
||||
PatchRawResponse(ctx context.Context, endpoint string, payload interface{}) (*ResponDTOVclaim, error)
|
||||
DeleteRawResponse(ctx context.Context, endpoint string) (*ResponDTOVclaim, error)
|
||||
}
|
||||
|
||||
// Service struct for VClaim service
|
||||
type Service struct {
|
||||
config config.BpjsConfig
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
// Response structures
|
||||
type ResponMentahDTOVclaim struct {
|
||||
MetaData struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
} `json:"metaData"`
|
||||
Response string `json:"response"`
|
||||
}
|
||||
|
||||
type ResponDTOVclaim struct {
|
||||
MetaData struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
} `json:"metaData"`
|
||||
Response interface{} `json:"response"`
|
||||
}
|
||||
|
||||
// NewService creates a new VClaim service instance
|
||||
func NewService(cfg config.BpjsConfig) VClaimService {
|
||||
log.Info().
|
||||
Str("base_url", cfg.BaseURL).
|
||||
Dur("timeout", cfg.Timeout).
|
||||
Msg("Creating new VClaim service instance")
|
||||
|
||||
service := &Service{
|
||||
config: cfg,
|
||||
httpClient: &http.Client{
|
||||
Timeout: cfg.Timeout,
|
||||
},
|
||||
}
|
||||
return service
|
||||
}
|
||||
|
||||
// NewServiceFromConfig creates service from main config
|
||||
func NewServiceFromConfig(cfg *config.Config) VClaimService {
|
||||
return NewService(cfg.Bpjs)
|
||||
}
|
||||
|
||||
// NewServiceFromInterface creates service from interface (for backward compatibility)
|
||||
func NewServiceFromInterface(cfg interface{}) (VClaimService, error) {
|
||||
var bpjsConfig config.BpjsConfig
|
||||
|
||||
// Try to map from interface
|
||||
err := smapping.FillStruct(&bpjsConfig, smapping.MapFields(&cfg))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to map config: %w", err)
|
||||
}
|
||||
|
||||
if bpjsConfig.Timeout == 0 {
|
||||
bpjsConfig.Timeout = 30 * time.Second
|
||||
}
|
||||
|
||||
return NewService(bpjsConfig), nil
|
||||
}
|
||||
|
||||
// SetHTTPClient allows custom http client configuration
|
||||
func (s *Service) SetHTTPClient(client *http.Client) {
|
||||
s.httpClient = client
|
||||
}
|
||||
|
||||
// prepareRequest prepares HTTP request with required headers
|
||||
func (s *Service) prepareRequest(ctx context.Context, method, endpoint string, body io.Reader) (*http.Request, string, string, string, string, error) {
|
||||
fullURL := s.config.BaseURL + endpoint
|
||||
|
||||
log.Info().
|
||||
Str("method", method).
|
||||
Str("endpoint", endpoint).
|
||||
Str("full_url", fullURL).
|
||||
Msg("Preparing HTTP request")
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, method, fullURL, body)
|
||||
if err != nil {
|
||||
log.Error().
|
||||
Err(err).
|
||||
Str("method", method).
|
||||
Str("endpoint", endpoint).
|
||||
Msg("Failed to create HTTP request")
|
||||
return nil, "", "", "", "", fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
// Set headers using the SetHeader method
|
||||
consID, secretKey, userKey, tstamp, xSignature := s.config.SetHeader()
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-cons-id", consID)
|
||||
req.Header.Set("X-timestamp", tstamp)
|
||||
req.Header.Set("X-signature", xSignature)
|
||||
req.Header.Set("user_key", userKey)
|
||||
|
||||
log.Debug().
|
||||
Str("method", method).
|
||||
Str("endpoint", endpoint).
|
||||
Str("x_cons_id", consID).
|
||||
Str("x_timestamp", tstamp).
|
||||
Str("user_key", userKey).
|
||||
Msg("Request headers set")
|
||||
|
||||
return req, consID, secretKey, tstamp, xSignature, nil
|
||||
}
|
||||
|
||||
// processResponse processes response from VClaim API
|
||||
func (s *Service) processResponse(res *http.Response, consID, secretKey, tstamp string) (*ResponDTOVclaim, error) {
|
||||
defer res.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read response body: %w", err)
|
||||
}
|
||||
|
||||
if res.StatusCode >= 400 {
|
||||
return nil, fmt.Errorf("HTTP error: %d - %s", res.StatusCode, string(body))
|
||||
}
|
||||
|
||||
// Parse raw response
|
||||
var respMentah ResponMentahDTOVclaim
|
||||
if err := json.Unmarshal(body, &respMentah); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal raw response: %w", err)
|
||||
}
|
||||
|
||||
// Create final response
|
||||
finalResp := &ResponDTOVclaim{
|
||||
MetaData: respMentah.MetaData,
|
||||
}
|
||||
|
||||
// Check if response needs decryption
|
||||
if respMentah.Response == "" {
|
||||
return finalResp, nil
|
||||
}
|
||||
|
||||
// Try to parse as JSON first (unencrypted response)
|
||||
var tempResp interface{}
|
||||
if json.Unmarshal([]byte(respMentah.Response), &tempResp) == nil {
|
||||
finalResp.Response = tempResp
|
||||
return finalResp, nil
|
||||
}
|
||||
|
||||
// Check if response looks like HTML or error message (don't try to decrypt)
|
||||
if strings.HasPrefix(respMentah.Response, "<") || strings.Contains(respMentah.Response, "error") {
|
||||
finalResp.Response = respMentah.Response
|
||||
return finalResp, nil
|
||||
}
|
||||
|
||||
// Decrypt response using the same timestamp from the request
|
||||
decryptionKey := consID + secretKey + tstamp
|
||||
|
||||
log.Debug().
|
||||
Str("consID", consID).
|
||||
Str("tstamp", tstamp).
|
||||
Int("key_length", len(decryptionKey)).
|
||||
Msg("Decryption key components")
|
||||
|
||||
respDecrypt, err := ResponseVclaim(respMentah.Response, decryptionKey)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to decrypt response")
|
||||
return nil, fmt.Errorf("failed to decrypt response: %w", err)
|
||||
}
|
||||
|
||||
// Try to unmarshal decrypted response as JSON
|
||||
if respDecrypt != "" {
|
||||
// Clean the decrypted response
|
||||
respDecrypt = cleanResponse(respDecrypt)
|
||||
|
||||
// Try multiple cleaning strategies
|
||||
cleaningStrategies := []string{
|
||||
respDecrypt,
|
||||
strings.TrimLeft(respDecrypt, "\ufeff\xfe\xef\xbb\xbf"),
|
||||
strings.TrimLeftFunc(respDecrypt, func(r rune) bool { return r < 32 && r != '\n' && r != '\r' && r != '\t' }),
|
||||
}
|
||||
|
||||
var jsonParseSuccess bool
|
||||
for i, cleaned := range cleaningStrategies {
|
||||
if err := json.Unmarshal([]byte(cleaned), &finalResp.Response); err == nil {
|
||||
log.Info().
|
||||
Int("strategy", i+1).
|
||||
Msg("Successfully parsed JSON with cleaning strategy")
|
||||
jsonParseSuccess = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !jsonParseSuccess {
|
||||
// If all JSON parsing fails, store as string
|
||||
log.Warn().Msg("All JSON parsing strategies failed, storing as string")
|
||||
finalResp.Response = respDecrypt
|
||||
}
|
||||
}
|
||||
|
||||
return finalResp, nil
|
||||
}
|
||||
|
||||
// Get performs HTTP GET request
|
||||
func (s *Service) Get(ctx context.Context, endpoint string, result interface{}) error {
|
||||
resp, err := s.GetRawResponse(ctx, endpoint)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return mapToResult(resp, result)
|
||||
}
|
||||
|
||||
// Post performs HTTP POST request
|
||||
func (s *Service) Post(ctx context.Context, endpoint string, payload interface{}, result interface{}) error {
|
||||
resp, err := s.PostRawResponse(ctx, endpoint, payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return mapToResult(resp, result)
|
||||
}
|
||||
|
||||
// Put performs HTTP PUT request
|
||||
func (s *Service) Put(ctx context.Context, endpoint string, payload interface{}, result interface{}) error {
|
||||
var buf bytes.Buffer
|
||||
if payload != nil {
|
||||
if err := json.NewEncoder(&buf).Encode(payload); err != nil {
|
||||
return fmt.Errorf("failed to encode payload: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
req, consID, secretKey, tstamp, _, err := s.prepareRequest(ctx, http.MethodPut, endpoint, &buf)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
res, err := s.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to execute PUT request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := s.processResponse(res, consID, secretKey, tstamp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return mapToResult(resp, result)
|
||||
}
|
||||
|
||||
// Delete performs HTTP DELETE request
|
||||
func (s *Service) Delete(ctx context.Context, endpoint string, result interface{}) error {
|
||||
req, consID, secretKey, tstamp, _, err := s.prepareRequest(ctx, http.MethodDelete, endpoint, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
res, err := s.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to execute DELETE request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := s.processResponse(res, consID, secretKey, tstamp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return mapToResult(resp, result)
|
||||
}
|
||||
|
||||
// Patch performs HTTP PATCH request
|
||||
func (s *Service) Patch(ctx context.Context, endpoint string, payload interface{}, result interface{}) error {
|
||||
var buf bytes.Buffer
|
||||
if payload != nil {
|
||||
if err := json.NewEncoder(&buf).Encode(payload); err != nil {
|
||||
return fmt.Errorf("failed to encode payload: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
req, consID, secretKey, tstamp, _, err := s.prepareRequest(ctx, http.MethodPatch, endpoint, &buf)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
res, err := s.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to execute PATCH request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := s.processResponse(res, consID, secretKey, tstamp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return mapToResult(resp, result)
|
||||
}
|
||||
|
||||
// GetRawResponse returns raw response without mapping
|
||||
func (s *Service) GetRawResponse(ctx context.Context, endpoint string) (*ResponDTOVclaim, error) {
|
||||
req, consID, secretKey, tstamp, _, err := s.prepareRequest(ctx, http.MethodGet, endpoint, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
res, err := s.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to execute GET request: %w", err)
|
||||
}
|
||||
|
||||
return s.processResponse(res, consID, secretKey, tstamp)
|
||||
}
|
||||
|
||||
// PostRawResponse returns raw response without mapping
|
||||
func (s *Service) PostRawResponse(ctx context.Context, endpoint string, payload interface{}) (*ResponDTOVclaim, error) {
|
||||
var buf bytes.Buffer
|
||||
if payload != nil {
|
||||
if err := json.NewEncoder(&buf).Encode(payload); err != nil {
|
||||
return nil, fmt.Errorf("failed to encode payload: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
req, consID, secretKey, tstamp, _, err := s.prepareRequest(ctx, http.MethodPost, endpoint, &buf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
res, err := s.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to execute POST request: %w", err)
|
||||
}
|
||||
|
||||
return s.processResponse(res, consID, secretKey, tstamp)
|
||||
}
|
||||
|
||||
// PatchRawResponse returns raw response without mapping
|
||||
func (s *Service) PatchRawResponse(ctx context.Context, endpoint string, payload interface{}) (*ResponDTOVclaim, error) {
|
||||
var buf bytes.Buffer
|
||||
if payload != nil {
|
||||
if err := json.NewEncoder(&buf).Encode(payload); err != nil {
|
||||
return nil, fmt.Errorf("failed to encode payload: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
req, consID, secretKey, tstamp, _, err := s.prepareRequest(ctx, http.MethodPatch, endpoint, &buf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
res, err := s.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to execute PATCH request: %w", err)
|
||||
}
|
||||
|
||||
return s.processResponse(res, consID, secretKey, tstamp)
|
||||
}
|
||||
|
||||
// PutRawResponse returns raw response without mapping
|
||||
func (s *Service) PutRawResponse(ctx context.Context, endpoint string, payload interface{}) (*ResponDTOVclaim, error) {
|
||||
var buf bytes.Buffer
|
||||
if payload != nil {
|
||||
if err := json.NewEncoder(&buf).Encode(payload); err != nil {
|
||||
return nil, fmt.Errorf("failed to encode payload: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
req, consID, secretKey, tstamp, _, err := s.prepareRequest(ctx, http.MethodPut, endpoint, &buf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
res, err := s.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to execute PUT request: %w", err)
|
||||
}
|
||||
|
||||
return s.processResponse(res, consID, secretKey, tstamp)
|
||||
}
|
||||
|
||||
// DeleteRawResponse returns raw response without mapping
|
||||
func (s *Service) DeleteRawResponse(ctx context.Context, endpoint string) (*ResponDTOVclaim, error) {
|
||||
req, consID, secretKey, tstamp, _, err := s.prepareRequest(ctx, http.MethodDelete, endpoint, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
res, err := s.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to execute DELETE request: %w", err)
|
||||
}
|
||||
|
||||
return s.processResponse(res, consID, secretKey, tstamp)
|
||||
}
|
||||
|
||||
// mapToResult maps the final response to the result interface
|
||||
func mapToResult(resp *ResponDTOVclaim, result interface{}) error {
|
||||
respBytes, err := json.Marshal(resp)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal final response: %w", err)
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(respBytes, result); err != nil {
|
||||
return fmt.Errorf("failed to unmarshal to result: %w", err)
|
||||
}
|
||||
|
||||
// Handle BPJS peserta response structure
|
||||
if pesertaResp, ok := result.(*peserta.PesertaResponse); ok {
|
||||
if resp.Response != nil {
|
||||
if responseMap, ok := resp.Response.(map[string]interface{}); ok {
|
||||
if pesertaMap, ok := responseMap["peserta"]; ok {
|
||||
pesertaBytes, _ := json.Marshal(pesertaMap)
|
||||
var pd peserta.PesertaData
|
||||
json.Unmarshal(pesertaBytes, &pd)
|
||||
pesertaResp.Data = &pd
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Backward compatibility functions
|
||||
func GetRequest(endpoint string, cfg interface{}) interface{} {
|
||||
service, err := NewServiceFromInterface(cfg)
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to create service: %v\n", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
resp, err := service.GetRawResponse(ctx, endpoint)
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to get response: %v\n", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
return resp
|
||||
}
|
||||
|
||||
func PostRequest(endpoint string, cfg interface{}, data interface{}) interface{} {
|
||||
service, err := NewServiceFromInterface(cfg)
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to create service: %v\n", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
resp, err := service.PostRawResponse(ctx, endpoint, data)
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to post response: %v\n", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
return resp
|
||||
}
|
||||
|
||||
func cleanResponse(s string) string {
|
||||
// Remove UTF-8 BOM dan variasi BOM lainnya
|
||||
s = strings.TrimPrefix(s, "\xef\xbb\xbf") // UTF-8 BOM
|
||||
s = strings.TrimPrefix(s, "\ufeff") // Unicode BOM
|
||||
s = strings.TrimPrefix(s, "\ufffe") // Unicode BOM (reverse)
|
||||
s = strings.TrimPrefix(s, "\xff\xfe") // UTF-16 LE BOM
|
||||
s = strings.TrimPrefix(s, "\xfe\xff") // UTF-16 BE BOM
|
||||
|
||||
// Remove karakter control dan non-printable
|
||||
var result strings.Builder
|
||||
for _, r := range s {
|
||||
if r >= 32 && r <= 126 || r == '\n' || r == '\r' || r == '\t' {
|
||||
result.WriteRune(r)
|
||||
} else if r > 126 && unicode.IsPrint(r) {
|
||||
// Allow Unicode printable characters
|
||||
result.WriteRune(r)
|
||||
}
|
||||
// Skip semua karakter lainnya (termasuk BOM fragments)
|
||||
}
|
||||
|
||||
cleaned := result.String()
|
||||
cleaned = strings.TrimSpace(cleaned)
|
||||
|
||||
// Cari dan ekstrak JSON yang valid
|
||||
if idx := strings.Index(cleaned, "{"); idx >= 0 {
|
||||
cleaned = cleaned[idx:]
|
||||
// Find matching closing brace
|
||||
if endIdx := findMatchingBrace(cleaned); endIdx > 0 {
|
||||
cleaned = cleaned[:endIdx+1]
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("cleanResponse: Final cleaned length: %d", len(cleaned))
|
||||
log.Printf("cleanResponse: Final result preview: %s", cleaned[:min(200, len(cleaned))])
|
||||
return cleaned
|
||||
}
|
||||
|
||||
// Fungsi helper untuk menemukan closing brace yang matching
|
||||
func findMatchingBrace(s string) int {
|
||||
if len(s) == 0 || s[0] != '{' {
|
||||
return -1
|
||||
}
|
||||
|
||||
braceCount := 0
|
||||
inString := false
|
||||
escaped := false
|
||||
|
||||
for i, char := range s {
|
||||
if escaped {
|
||||
escaped = false
|
||||
continue
|
||||
}
|
||||
|
||||
if char == '\\' {
|
||||
escaped = true
|
||||
continue
|
||||
}
|
||||
|
||||
if char == '"' && !escaped {
|
||||
inString = !inString
|
||||
continue
|
||||
}
|
||||
|
||||
if !inString {
|
||||
if char == '{' {
|
||||
braceCount++
|
||||
} else if char == '}' {
|
||||
braceCount--
|
||||
if braceCount == 0 {
|
||||
return i
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return -1
|
||||
}
|
||||
Reference in New Issue
Block a user