feat(handler): server 模式健康档案查询端点(T-208)

- GET /api/health-record/find 按 idCard/phrid/personName/empiId 查询
- 回写平台完整响应(Result.Raw),未建模字段不丢失
- 抽 buildOSIClient 共用构造,verify 与 server 复用
- 默认仅绑 127.0.0.1(端点返回真实档案 PII,避免暴露局域网)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
ila
2026-07-08 00:05:22 +08:00
co-authored by Claude Opus 4.8
parent 55289e0746
commit 47eaf1051e
6 changed files with 175 additions and 15 deletions
+58
View File
@@ -0,0 +1,58 @@
package handler
import (
"encoding/json"
"net/http"
"chis_osi/osi"
)
// HealthRecordHandler 暴露健康档案查询的 HTTP 入口。
type HealthRecordHandler struct {
client *osi.Client
}
func NewHealthRecordHandler(client *osi.Client) *HealthRecordHandler {
return &HealthRecordHandler{client: client}
}
// Find 处理 GET /api/health-record/find?idCard=..|phrid=..|personName=..|empiId=..
// 直接回写平台完整响应({code,message,data:[...]}),不做字段裁剪——查询响应可能含
// Go 结构体未建模的字段,回写原始 JSON 才能看到完整档案内容。
func (h *HealthRecordHandler) Find(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
writeJSONError(w, http.StatusMethodNotAllowed, "only GET is supported")
return
}
q := r.URL.Query()
query := osi.FindHealthRecordQuery{
IDCard: q.Get("idCard"),
PHRID: q.Get("phrid"),
PersonName: q.Get("personName"),
EMPIID: q.Get("empiId"),
}
if query.IDCard == "" && query.PHRID == "" && query.PersonName == "" && query.EMPIID == "" {
writeJSONError(w, http.StatusBadRequest, "provide one of: idCard, phrid, personName, empiId")
return
}
_, result, err := h.client.FindHealthRecord(r.Context(), query)
// 拿到平台响应就原样回写(成功或业务错误都含 code/message),便于查看完整内容。
if len(result.Raw) > 0 {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_, _ = w.Write(result.Raw)
return
}
if err != nil {
writeJSONError(w, http.StatusBadGateway, err.Error())
return
}
writeJSONError(w, http.StatusBadGateway, "empty response from OSI")
}
func writeJSONError(w http.ResponseWriter, status int, msg string) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]string{"error": msg})
}
+51
View File
@@ -0,0 +1,51 @@
package handler
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"chis_osi/osi"
)
func TestHealthRecordFindReturnsRawPlatformResponse(t *testing.T) {
osiServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"code":"01","message":"操作成功","data":[{"healthRecord":{"phrId":"phr-001","adressNumber":"下围村1号"}}]}`))
}))
defer osiServer.Close()
transport, err := osi.NewTransport(osi.TransportConfig{Timeout: time.Second})
if err != nil {
t.Fatalf("NewTransport: %v", err)
}
client := osi.NewClient(osi.ClientConfig{BaseURL: osiServer.URL, UserName: "dyytgw", Ask: "secret", Transport: transport})
h := NewHealthRecordHandler(client)
req := httptest.NewRequest(http.MethodGet, "/api/health-record/find?idCard=440100199001011234", nil)
rec := httptest.NewRecorder()
h.Find(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d", rec.Code)
}
body, _ := io.ReadAll(rec.Body)
// 完整回写:未建模字段 adressNumber 也应原样出现
if !strings.Contains(string(body), `"phr-001"`) || !strings.Contains(string(body), "adressNumber") {
t.Fatalf("body missing full archive content: %s", body)
}
}
func TestHealthRecordFindRequiresIdentifier(t *testing.T) {
h := NewHealthRecordHandler(nil) // 无标识符时在触达 client 前就返回 400
req := httptest.NewRequest(http.MethodGet, "/api/health-record/find", nil)
rec := httptest.NewRecorder()
h.Find(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400", rec.Code)
}
}
+9
View File
@@ -30,6 +30,7 @@ func parseMode(raw string) (appMode, error) {
func main() { func main() {
modeFlag := flag.String("mode", string(modeServer), "运行模式:server 或 deliver") modeFlag := flag.String("mode", string(modeServer), "运行模式:server 或 deliver")
configPath := flag.String("config", "config.yaml", "配置文件路径") configPath := flag.String("config", "config.yaml", "配置文件路径")
addr := flag.String("addr", "127.0.0.1:8080", "server 模式 HTTP 监听地址(默认仅本机,档案含 PII 勿绑 0.0.0.0)")
verifyJKDA := flag.Bool("verify-jkda", false, "阶段0联调验收:从 OSI_VERIFY_ID_CARD 读取身份证并查询 JKDA00002") verifyJKDA := flag.Bool("verify-jkda", false, "阶段0联调验收:从 OSI_VERIFY_ID_CARD 读取身份证并查询 JKDA00002")
flag.Parse() flag.Parse()
@@ -60,6 +61,14 @@ func main() {
return return
} }
if mode == modeServer {
if err := runServer(cfg, *addr); err != nil {
fmt.Fprintf(os.Stderr, "server: %v\n", err)
os.Exit(1)
}
return
}
fmt.Printf("chis_osi mode=%s\n", mode) fmt.Printf("chis_osi mode=%s\n", mode)
} }
+29
View File
@@ -0,0 +1,29 @@
package main
import (
"time"
"chis_osi/config"
"chis_osi/osi"
)
// buildOSIClient 用配置里的 OSI 段组装带签名/代理的薄客户端,供验证入口与 server 模式复用。
func buildOSIClient(cfg config.Config) (*osi.Client, error) {
transport, err := osi.NewTransport(osi.TransportConfig{
Timeout: time.Duration(cfg.OSI.TimeoutSec) * time.Second,
Socks5Proxy: cfg.OSI.Socks5Proxy,
})
if err != nil {
return nil, err
}
return osi.NewClient(osi.ClientConfig{
BaseURL: cfg.OSI.BaseURL,
OrgCode: cfg.OSI.OrgCode,
DeviceSN: cfg.OSI.DeviceSN,
UserName: cfg.OSI.UserName,
Ask: cfg.OSI.Ask,
OperateUser: cfg.OSI.OperateUser,
OperateUnit: cfg.OSI.OrgCode,
Transport: transport,
}), nil
}
+27
View File
@@ -0,0 +1,27 @@
package main
import (
"fmt"
"net/http"
"chis_osi/config"
"chis_osi/handler"
)
// runServer 启动 server 模式 HTTP 服务,暴露健康档案查询端点。
func runServer(cfg config.Config, addr string) error {
client, err := buildOSIClient(cfg)
if err != nil {
return fmt.Errorf("build osi client: %w", err)
}
hr := handler.NewHealthRecordHandler(client)
mux := http.NewServeMux()
mux.HandleFunc("/api/health-record/find", hr.Find)
fmt.Printf("chis_osi server listening on %s\n", addr)
fmt.Printf(" GET http://%s/api/health-record/find?idCard=<身份证>\n", addr)
server := &http.Server{Addr: addr, Handler: mux}
return server.ListenAndServe()
}
+1 -15
View File
@@ -3,7 +3,6 @@ package main
import ( import (
"context" "context"
"fmt" "fmt"
"time"
"chis_osi/config" "chis_osi/config"
"chis_osi/osi" "chis_osi/osi"
@@ -20,23 +19,10 @@ func runJKDAFindCheck(ctx context.Context, cfg config.Config, idCard string) (jk
return jkdaFindCheckResult{}, fmt.Errorf("id card is required") return jkdaFindCheckResult{}, fmt.Errorf("id card is required")
} }
transport, err := osi.NewTransport(osi.TransportConfig{ client, err := buildOSIClient(cfg)
Timeout: time.Duration(cfg.OSI.TimeoutSec) * time.Second,
Socks5Proxy: cfg.OSI.Socks5Proxy,
})
if err != nil { if err != nil {
return jkdaFindCheckResult{}, err return jkdaFindCheckResult{}, err
} }
client := osi.NewClient(osi.ClientConfig{
BaseURL: cfg.OSI.BaseURL,
OrgCode: cfg.OSI.OrgCode,
DeviceSN: cfg.OSI.DeviceSN,
UserName: cfg.OSI.UserName,
Ask: cfg.OSI.Ask,
OperateUser: cfg.OSI.OperateUser,
OperateUnit: cfg.OSI.OrgCode,
Transport: transport,
})
records, result, err := client.FindHealthRecord(ctx, osi.FindHealthRecordQuery{IDCard: idCard}) records, result, err := client.FindHealthRecord(ctx, osi.FindHealthRecordQuery{IDCard: idCard})
check := jkdaFindCheckResult{Code: result.Code, Message: result.Message, DataCount: len(records)} check := jkdaFindCheckResult{Code: result.Code, Message: result.Message, DataCount: len(records)}