Sobes.tech
Junior — Senior

Optimization and restructuring of Go code

livecode

Task condition

Perform refactoring of the provided Go code snippet, improving readability, removing duplication, and eliminating potential vulnerabilities. Keep the original business logic intact.

func checkName(name string) error {
    if len(name) > 50 {
        return errors.New("invalid name length")
    }
    return nil
}

func checkPhone(phone string) error {
    if len(phone) != 11 {
        return errors.New("invalid phone format")
    }
    return nil
}

type Account struct {
    Id        int       `json:"id"`
    Name      string    `json:"name"`
    Password  string    `json:"password"`
    Phone     string    `json:"phone"`
    IsAdmin   bool      `json:"is_admin"`
    CreatedAt time.Time `json:"created_at"`
    UpdatedAt time.Time `json:"updated_at"`
}

type AccountRepo interface {
    Find(sql string) *Account
    Save(account *Account)
}

type AccountHandler struct {
    repo   AccountRepo
    logger *zap.Logger
}

func NewAccountHandler(repo AccountRepo) *AccountHandler {
    handler := &AccountHandler{repo: repo}
    if os.Getenv("ENV") == "prod" {
        handler.logger, _ = zap.NewProduction()
    } else {
        handler.logger, _ = zap.NewDevelopment()
    }
    return handler
}

func (h *AccountHandler) Login(c *gin.Context) {
    login := c.GetString("username")
    pass := c.GetString("password")

    acc := h.repo.Find(fmt.Sprintf("SELECT * FROM user WHERE username = %s", login))
    if acc == nil {
        c.JSON(http.StatusOK, nil)
        return
    }

    if acc.Password == pass {
        c.SetCookie("auth_session_id", uuid.New().String(), 3600, "/", "", false, false)
        c.JSON(http.StatusOK, map[string]string{"status": "ok"})
    }
}

func (h *AccountHandler) ProcessRequest(c *gin.Context) {
    requesterId := c.GetInt("auth_user_id")
    requester := h.repo.Find(fmt.Sprintf("SELECT * FROM user WHERE id = %d", requesterId))

    targetId := c.Query("id")
    target := h.repo.Find(fmt.Sprintf("SELECT * FROM user WHERE id = %s", targetId))

    if requester.IsAdmin || requester.Id == target.Id {
        if c.Request.Method == "POST" {
            bytes, _ := io.ReadAll(c.Request.Body)
            var body map[string]string
            json.Unmarshal(bytes, &body)
        }
    }
}

The task aims to extract common checks, improve naming, replace direct parameter substitution in SQL queries, and unify code style.