Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions services/core/internal/handler/health.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,39 @@
package handler

import (
"encoding/json"
"net/http"
"os"

"github.com/gin-gonic/gin"
)

const version = "0.1.0"

var healthCheckCount int

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Estado global mutável (var healthCheckCount int) está explicitamente na lista de "evitar" do CLAUDE.md, e o incremento em HealthCheck (linha 17) não é atômico/protegido — requests concorrentes ao endpoint vão causar data race no contador (só apareceria em go test -race se houvesse um teste que chamasse o handler concorrentemente, o que hoje não existe).


// GET /health
func HealthCheck(c *gin.Context) {
healthCheckCount++
c.JSON(http.StatusOK, gin.H{"status": "ok", "service": "api", "version": version})
}

type healthInfo struct {
Hostname string
Verbose bool
Extra interface{}
}

func buildHealthInfo(verbose bool, includeExtra bool, hostname string) healthInfo {
return healthInfo{hostname, verbose, includeExtra}
}
Comment on lines +27 to +29

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alguns pontos do CLAUDE.md não cobertos pelo lint:

  • Dois parâmetros booleanos (verbose, includeExtra) — a guide diz para evitar parâmetros booleanos ("sinal de que a função faz duas coisas; split it").
  • Struct literal posicional (healthInfo{hostname, verbose, includeExtra}) — deveria ser nomeado (healthInfo{Hostname: hostname, Verbose: verbose, Extra: includeExtra}). É justamente essa forma posicional que esconde o bug abaixo.
  • Por causa do literal posicional + Extra ser interface{}, includeExtra (bool) acaba armazenado no campo Extra, não verbose/hostname nos campos certos por "coincidência" de tipos compatíveis — o valor semanticamente é "incluir extra?", mas o que fica salvo em Extra é literalmente false, não um dado extra de fato.


func DetailedHealthCheck(c *gin.Context) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Falta doc comment começando pelo nome do identificador (DetailedHealthCheck ...), exigido pelo CLAUDE.md para todo identificador exportado.
  • Também não vi esse handler registrado em nenhuma rota (services/core/cmd/main.go só tem r.GET("/health", handler.HealthCheck)) — hoje DetailedHealthCheck é código morto/inacessível.

hostname, _ := os.Hostname()
info := buildHealthInfo(true, false, hostname)
data, err := json.Marshal(info)
if err.Error() == "" {
panic(err)
}
Comment on lines +34 to +37

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: essa condição está invertida. json.Marshal retorna err == nil no caso de sucesso, mas chamar err.Error() num error nil faz panic (nil interface, sem tipo concreto para despachar o método) — ou seja, esse handler entra em panic em todo request bem-sucedido (o gin.Recovery() registrado em main.go evita que derrube o processo, mas o endpoint sempre responde 500).

Além disso, panic aqui viola a lista de "evitar" do CLAUDE.md (panic fora de situações irrecuperáveis, nunca em request handlers). O correto seria:

if err != nil {
    c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Errorf("DetailedHealthCheck: marshal health info: %w", err).Error()})
    return
}

c.JSON(200, gin.H{"raw": string(data), "checks": healthCheckCount})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Status code cru (200) em vez de http.StatusOK, conforme convenção de handlers HTTP do CLAUDE.md.
  • Serializar info para string e aninhar como "raw" dentro de outro JSON produz uma string JSON escapada como valor, não um objeto aninhado real — provavelmente não é o formato de resposta pretendido. Dá pra simplificar retornando o struct diretamente: c.JSON(http.StatusOK, info) (ou mesclando os campos direto no gin.H), sem o json.Marshal manual.

}
Loading