From c500d75b122a58a013ce75eef840e9632bd1bda6 Mon Sep 17 00:00:00 2001 From: hhs <386998068.com> Date: Sun, 5 Apr 2026 15:03:56 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E7=9F=A5=E8=AF=86=E5=9B=BE=E8=B0=B1?= =?UTF-8?q?=E6=B5=8B=E8=AF=95api?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/data.json | 306 +++++++++++++++++++++++++++++ backend/go.mod | 37 ++++ backend/go.sum | 80 ++++++++ backend/handlers/graph_handler.go | 34 ++++ backend/handlers/node_handler.go | 69 +++++++ backend/handlers/search_handler.go | 33 ++++ backend/main.go | 73 +++++++ backend/models/graph.go | 26 +++ backend/models/nodes.go | 23 +++ backend/services/data_service.go | 161 +++++++++++++++ frontend/src/services/graphApi.ts | 2 +- 11 files changed, 843 insertions(+), 1 deletion(-) create mode 100644 backend/data.json create mode 100644 backend/go.mod create mode 100644 backend/go.sum create mode 100644 backend/handlers/graph_handler.go create mode 100644 backend/handlers/node_handler.go create mode 100644 backend/handlers/search_handler.go create mode 100644 backend/main.go create mode 100644 backend/models/graph.go create mode 100644 backend/models/nodes.go create mode 100644 backend/services/data_service.go diff --git a/backend/data.json b/backend/data.json new file mode 100644 index 0000000..98ea83f --- /dev/null +++ b/backend/data.json @@ -0,0 +1,306 @@ +{ + "nodes": [ + { + "id": "1", + "label": "人工智能", + "type": "概念", + "properties": { + "importance": 1, + "description": "计算机科学的一个分支,致力于创建能够执行通常需要人类智能的任务的机器", + "aliases": ["机器智能", "AI"] + }, + "style": { + "fill": "#FF6B6B", + "stroke": "#EE5A5A", + "lineWidth": 3 + } + }, + { + "id": "2", + "label": "机器学习", + "type": "概念", + "properties": { + "importance": 0.9, + "description": "人工智能的一个子领域,让计算机系统能够从数据中学习和改进" + }, + "style": { + "fill": "#4ECDC4", + "stroke": "#45B7B0", + "lineWidth": 2 + } + }, + { + "id": "3", + "label": "深度学习", + "type": "概念", + "properties": { + "importance": 0.8, + "description": "基于人工神经网络的机器学习方法" + }, + "style": { + "fill": "#45B7D1", + "stroke": "#3DA4BA", + "lineWidth": 2 + } + }, + { + "id": "4", + "label": "神经网络", + "type": "概念", + "properties": { + "importance": 0.7, + "description": "受人脑启发的计算模型" + } + }, + { + "id": "5", + "label": "TensorFlow", + "type": "工具", + "properties": { + "importance": 0.6, + "language": "Python, C++", + "author": "Google" + }, + "style": { + "fill": "#FFA07A", + "stroke": "#FF7F50" + } + }, + { + "id": "6", + "label": "PyTorch", + "type": "工具", + "properties": { + "importance": 0.6, + "language": "Python", + "author": "Meta" + }, + "style": { + "fill": "#FFA07A", + "stroke": "#FF7F50" + } + }, + { + "id": "7", + "label": "自然语言处理", + "type": "应用", + "properties": { + "importance": 0.7, + "description": "处理和理解人类语言的技术" + } + }, + { + "id": "8", + "label": "计算机视觉", + "type": "应用", + "properties": { + "importance": 0.7, + "description": "让计算机理解和解析视觉信息" + } + }, + { + "id": "9", + "label": "强化学习", + "type": "概念", + "properties": { + "importance": 0.6, + "description": "通过与环境交互来学习最优策略" + } + }, + { + "id": "10", + "label": "监督学习", + "type": "概念", + "properties": { + "importance": 0.5, + "description": "使用标记数据进行学习" + } + }, + { + "id": "11", + "label": "GPT", + "type": "应用", + "properties": { + "importance": 0.8, + "author": "OpenAI", + "description": "Generative Pre-trained Transformer" + } + }, + { + "id": "12", + "label": "CNN", + "type": "概念", + "properties": { + "importance": 0.6, + "description": "卷积神经网络,用于处理网格状数据" + } + }, + { + "id": "13", + "label": "RNN", + "type": "概念", + "properties": { + "importance": 0.6, + "description": "循环神经网络,用于处理序列数据" + } + }, + { + "id": "14", + "label": "数据挖掘", + "type": "应用", + "properties": { + "importance": 0.5, + "description": "从大量数据中发现模式和知识" + } + } + ], + "edges": [ + { + "id": "e1", + "source": "1", + "target": "2", + "label": "包含", + "type": "关系", + "style": { + "stroke": "#95A5A6", + "lineWidth": 2 + } + }, + { + "id": "e2", + "source": "2", + "target": "3", + "label": "子领域", + "type": "关系", + "style": { + "stroke": "#95A5A6", + "lineWidth": 2 + } + }, + { + "id": "e3", + "source": "3", + "target": "4", + "label": "基于", + "type": "技术依赖", + "style": { + "stroke": "#3498DB", + "lineWidth": 2 + } + }, + { + "id": "e4", + "source": "3", + "target": "5", + "label": "框架", + "type": "工具关系", + "style": { + "stroke": "#E74C3C", + "lineWidth": 1 + } + }, + { + "id": "e5", + "source": "3", + "target": "6", + "label": "框架", + "type": "工具关系", + "style": { + "stroke": "#E74C3C", + "lineWidth": 1 + } + }, + { + "id": "e6", + "source": "1", + "target": "7", + "label": "应用", + "type": "应用领域", + "style": { + "stroke": "#2ECC71", + "lineWidth": 2 + } + }, + { + "id": "e7", + "source": "1", + "target": "8", + "label": "应用", + "type": "应用领域", + "style": { + "stroke": "#2ECC71", + "lineWidth": 2 + } + }, + { + "id": "e8", + "source": "2", + "target": "9", + "label": "包含", + "type": "关系" + }, + { + "id": "e9", + "source": "2", + "target": "10", + "label": "包含", + "type": "关系" + }, + { + "id": "e10", + "source": "7", + "target": "11", + "label": "技术实现", + "type": "技术依赖" + }, + { + "id": "e11", + "source": "3", + "target": "12", + "label": "主要架构", + "type": "技术依赖" + }, + { + "id": "e12", + "source": "3", + "target": "13", + "label": "主要架构", + "type": "技术依赖" + }, + { + "id": "e13", + "source": "8", + "target": "12", + "label": "核心技术", + "type": "技术依赖" + }, + { + "id": "e14", + "source": "7", + "target": "13", + "label": "核心技术", + "type": "技术依赖" + }, + { + "id": "e15", + "source": "2", + "target": "14", + "label": "相关技术", + "type": "相关" + }, + { + "id": "e16", + "source": "5", + "target": "12", + "label": "支持", + "type": "技术支持" + }, + { + "id": "e17", + "source": "6", + "target": "13", + "label": "支持", + "type": "技术支持" + } + ] +} \ No newline at end of file diff --git a/backend/go.mod b/backend/go.mod new file mode 100644 index 0000000..3a3008c --- /dev/null +++ b/backend/go.mod @@ -0,0 +1,37 @@ +module knowledge-graph-backend + +go 1.26.1 + +require ( + github.com/bytedance/gopkg v0.1.4 // indirect + github.com/bytedance/sonic v1.15.0 // indirect + github.com/bytedance/sonic/loader v0.5.1 // indirect + github.com/cloudwego/base64x v0.1.6 // indirect + github.com/gabriel-vasile/mimetype v1.4.13 // indirect + github.com/gin-contrib/cors v1.7.7 // indirect + github.com/gin-contrib/sse v1.1.1 // indirect + github.com/gin-gonic/gin v1.12.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.30.2 // indirect + github.com/goccy/go-json v0.10.6 // indirect + github.com/goccy/go-yaml v1.19.2 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.3.0 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.3.0 // indirect + github.com/quic-go/qpack v0.6.0 // indirect + github.com/quic-go/quic-go v0.59.0 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.3.1 // indirect + go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect + golang.org/x/arch v0.25.0 // indirect + golang.org/x/crypto v0.49.0 // indirect + golang.org/x/net v0.52.0 // indirect + golang.org/x/sys v0.42.0 // indirect + golang.org/x/text v0.35.0 // indirect + google.golang.org/protobuf v1.36.11 // indirect +) diff --git a/backend/go.sum b/backend/go.sum new file mode 100644 index 0000000..a07a2c9 --- /dev/null +++ b/backend/go.sum @@ -0,0 +1,80 @@ +github.com/bytedance/gopkg v0.1.4 h1:oZnQwnX82KAIWb7033bEwtxvTqXcYMxDBaQxo5JJHWM= +github.com/bytedance/gopkg v0.1.4/go.mod h1:v1zWfPm21Fb+OsyXN2VAHdL6TBb2L88anLQgdyje6R4= +github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE= +github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k= +github.com/bytedance/sonic/loader v0.5.1 h1:Ygpfa9zwRCCKSlrp5bBP/b/Xzc3VxsAW+5NIYXrOOpI= +github.com/bytedance/sonic/loader v0.5.1/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo= +github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= +github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM= +github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= +github.com/gin-contrib/cors v1.7.7 h1:Oh9joP463x7Mw72vhvJ61YQm8ODh9b04YR7vsOErD0Q= +github.com/gin-contrib/cors v1.7.7/go.mod h1:K5tW0RkzJtWSiOdikXloy8VEZlgdVNpHNw8FpjUPNrE= +github.com/gin-contrib/sse v1.1.1 h1:uGYpNwTacv5R68bSGMapo62iLTRa9l5zxGCps4hK6ko= +github.com/gin-contrib/sse v1.1.1/go.mod h1:QXzuVkA0YO7o/gun03UI1Q+FTI8ZV/n5t03kIQAI89s= +github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8= +github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.30.2 h1:JiFIMtSSHb2/XBUbWM4i/MpeQm9ZK2xqPNk8vgvu5JQ= +github.com/go-playground/validator/v10 v10.30.2/go.mod h1:mAf2pIOVXjTEBrwUMGKkCWKKPs9NheYGabeB04txQSc= +github.com/goccy/go-json v0.10.6 h1:p8HrPJzOakx/mn/bQtjgNjdTcN+/S6FcG2CTtQOrHVU= +github.com/goccy/go-json v0.10.6/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= +github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= +github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pelletier/go-toml/v2 v2.3.0 h1:k59bC/lIZREW0/iVaQR8nDHxVq8OVlIzYCOJf421CaM= +github.com/pelletier/go-toml/v2 v2.3.0/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= +github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= +github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw= +github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY= +github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= +go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE= +go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0= +golang.org/x/arch v0.25.0 h1:qnk6Ksugpi5Bz32947rkUgDt9/s5qvqDPl/gBKdMJLE= +golang.org/x/arch v0.25.0/go.mod h1:0X+GdSIP+kL5wPmpK7sdkEVTt2XoYP0cSjQSbZBwOi8= +golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4= +golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA= +golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0= +golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= +golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8= +golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/backend/handlers/graph_handler.go b/backend/handlers/graph_handler.go new file mode 100644 index 0000000..2718f7a --- /dev/null +++ b/backend/handlers/graph_handler.go @@ -0,0 +1,34 @@ +package handlers + +import ( + "net/http" + + "github.com/gin-gonic/gin" + "knowledge-graph-backend/services" +) + +type GraphHandler struct { + dataService *services.DataService +} + +func NewGraphHandler(dataService *services.DataService) *GraphHandler { + return &GraphHandler{ + dataService: dataService, + } +} + +func (h *GraphHandler) GetGraphData(c *gin.Context) { + data := h.dataService.GetGraphData() + c.JSON(http.StatusOK, data) +} + +func (h *GraphHandler) GetStats(c *gin.Context) { + stats := h.dataService.GetStats() + c.JSON(http.StatusOK, gin.H{ + "stats": stats, + "timestamp": gin.H{ + "totalNodes": stats["totalNodes"], + "totalEdges": stats["totalEdges"], + }, + }) +} diff --git a/backend/handlers/node_handler.go b/backend/handlers/node_handler.go new file mode 100644 index 0000000..feb00e3 --- /dev/null +++ b/backend/handlers/node_handler.go @@ -0,0 +1,69 @@ +package handlers + +import ( + "net/http" + + "github.com/gin-gonic/gin" + "knowledge-graph-backend/services" +) + +type NodeHandler struct { + dataService *services.DataService +} + +func NewNodeHandler(dataService *services.DataService) *NodeHandler { + return &NodeHandler{ + dataService: dataService, + } +} + +func (h *NodeHandler) GetNodeByID(c *gin.Context) { + nodeID := c.Param("id") + if nodeID == "" { + c.JSON(http.StatusBadRequest, gin.H{ + "error": "Bad Request", + "message": "Node ID is required", + }) + return + } + + node, found := h.dataService.GetNodeByID(nodeID) + if !found { + c.JSON(http.StatusNotFound, gin.H{ + "error": "Not Found", + "message": "Node with ID '" + nodeID + "' not found", + }) + return + } + + c.JSON(http.StatusOK, node) +} + +func (h *NodeHandler) GetNeighbors(c *gin.Context) { + nodeID := c.Param("id") + if nodeID == "" { + c.JSON(http.StatusBadRequest, gin.H{ + "error": "Bad Request", + "message": "Node ID is required", + }) + return + } + + neighbors, found := h.dataService.GetNeighbors(nodeID) + if !found { + c.JSON(http.StatusNotFound, gin.H{ + "error": "Not Found", + "message": "Node with ID '" + nodeID + "' not found", + }) + return + } + + c.JSON(http.StatusOK, neighbors) +} + +func (h *NodeHandler) AddCustomHeaders(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{ + "message": "With CORS headers", + "origin": c.Request.Header.Get("Origin"), + }) +} diff --git a/backend/handlers/search_handler.go b/backend/handlers/search_handler.go new file mode 100644 index 0000000..b344728 --- /dev/null +++ b/backend/handlers/search_handler.go @@ -0,0 +1,33 @@ +package handlers + +import ( + "net/http" + + "github.com/gin-gonic/gin" + "knowledge-graph-backend/services" +) + +type SearchHandler struct { + dataService *services.DataService +} + +func NewSearchHandler(dataService *services.DataService) *SearchHandler { + return &SearchHandler{ + dataService: dataService, + } +} + +func (h *SearchHandler) SearchNodes(c *gin.Context) { + query := c.Query("q") + if query == "" { + c.JSON(http.StatusBadRequest, gin.H{ + "error": "Bad Request", + "message": "Query parameter 'q' is required", + }) + return + } + + results := h.dataService.SearchNodes(query) + + c.JSON(http.StatusOK, results) +} diff --git a/backend/main.go b/backend/main.go new file mode 100644 index 0000000..f7e3fe3 --- /dev/null +++ b/backend/main.go @@ -0,0 +1,73 @@ +package main + +import ( + "log" + "net/http" + + "github.com/gin-contrib/cors" + "github.com/gin-gonic/gin" + + "knowledge-graph-backend/handlers" + "knowledge-graph-backend/services" +) + +const ( + PORT = "3001" + DATA_FILE = "data.json" +) + +func main() { + + dataService, err := services.NewDataService(DATA_FILE) + if err != nil { + log.Fatalf("Failed to initialize data service: %v", err) + } + + graphHandler := handlers.NewGraphHandler(dataService) + searchHandler := handlers.NewSearchHandler(dataService) + nodeHandler := handlers.NewNodeHandler(dataService) + + router := gin.Default() + + router.Use(cors.New(cors.Config{ + AllowOrigins: []string{"http://localhost:5173", "http://localhost:3000"}, + AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, + AllowHeaders: []string{"Origin", "Content-Type", "Authorization", "Accept"}, + ExposeHeaders: []string{"Content-Length", "Content-Type"}, + AllowCredentials: true, + MaxAge: 12 * 3600, + })) + + router.GET("/health", func(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{ + "status": "ok", + "message": "Knowledge Graph API is running", + "version": "1.0.0", + }) + }) + + api := router.Group("/api") + { + api.GET("/graph", graphHandler.GetGraphData) + api.GET("/graph/stats", graphHandler.GetStats) + + api.GET("/search", searchHandler.SearchNodes) + + api.GET("/nodes/:id", nodeHandler.GetNodeByID) + api.GET("/nodes/:id/neighbors", nodeHandler.GetNeighbors) + } + + log.Println("Knowledge Graph API Server running on http://localhost:" + PORT) + log.Println("Data file loaded from: " + DATA_FILE) + log.Println("Available endpoints:") + log.Println(" GET /health - Health check") + log.Println(" GET /api/graph - Get all graph data") + log.Println(" GET /api/graph/stats - Get graph statistics") + log.Println(" GET /api/search?q=query - Search nodes") + log.Println(" GET /api/nodes/:id - Get node by ID") + log.Println(" GET /api/nodes/:id/neighbors - Get node neighbors") + + if err := router.Run(":" + PORT); err != nil { + log.Fatalf("Failed to start server: %v", err) + } +} diff --git a/backend/models/graph.go b/backend/models/graph.go new file mode 100644 index 0000000..eeb6352 --- /dev/null +++ b/backend/models/graph.go @@ -0,0 +1,26 @@ +package models + +type Node struct { + ID string `json:"id"` + Label string `json:"label"` + Type string `json:"type,omitempty"` + Properties map[string]interface{} `json:"properties,omitempty"` + X float64 `json:"x,omitempty"` + Y float64 `json:"y,omitempty"` + Style map[string]interface{} `json:"style,omitempty"` +} + +type Edge struct { + ID string `json:"id"` + Source string `json:"source"` + Target string `json:"target"` + Label string `json:"label,omitempty"` + Type string `json:"type,omitempty"` + Properties map[string]interface{} `json:"properties,omitempty"` + Style map[string]interface{} `json:"style,omitempty"` +} + +type GraphData struct { + Nodes []Node `json:"nodes"` + Edges []Edge `json:"edges"` +} diff --git a/backend/models/nodes.go b/backend/models/nodes.go new file mode 100644 index 0000000..0e55cf0 --- /dev/null +++ b/backend/models/nodes.go @@ -0,0 +1,23 @@ +package models + +type NodeResponse struct { + ID string `json:"id" example:"1"` + Label string `json:"label" example:"人工智能"` + Type string `json:"type,omitempty" example:"概念"` + Properties map[string]interface{} `json:"properties,omitempty"` +} + +type NeighborResponse struct { + Nodes []Node `json:"nodes"` + Edges []Edge `json:"edges"` +} + +type SearchResponse struct { + Results []Node `json:"results"` + Count int `json:"count"` +} + +type ErrorResponse struct { + Error string `json:"error"` + Message string `json:"message"` +} diff --git a/backend/services/data_service.go b/backend/services/data_service.go new file mode 100644 index 0000000..d877858 --- /dev/null +++ b/backend/services/data_service.go @@ -0,0 +1,161 @@ +package services + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "log" + "os" + "strings" + "sync" + + "knowledge-graph-backend/models" +) + +type DataService struct { + data models.GraphData + mutex sync.RWMutex + filePath string +} + +func NewDataService(filePath string) (*DataService, error) { + ds := &DataService{ + filePath: filePath, + mutex: sync.RWMutex{}, + } + + if err := ds.loadData(); err != nil { + return nil, fmt.Errorf("failed to load data: %w", err) + } + + return ds, nil +} + +func (ds *DataService) loadData() error { + ds.mutex.Lock() + defer ds.mutex.Unlock() + + file, err := os.Open(ds.filePath) + if err != nil { + return fmt.Errorf("failed to open data file: %w", err) + } + defer file.Close() + + byteValue, err := ioutil.ReadAll(file) + if err != nil { + return fmt.Errorf("failed to read data file: %w", err) + } + + if err := json.Unmarshal(byteValue, &ds.data); err != nil { + return fmt.Errorf("failed to parse data file: %w", err) + } + + log.Printf("Loaded %d nodes and %d edges from %s", + len(ds.data.Nodes), len(ds.data.Edges), ds.filePath) + + return nil +} + +func (ds *DataService) GetGraphData() models.GraphData { + ds.mutex.RLock() + defer ds.mutex.RUnlock() + return ds.data +} + +func (ds *DataService) GetNodeByID(id string) (models.Node, bool) { + ds.mutex.RLock() + defer ds.mutex.RUnlock() + + for _, node := range ds.data.Nodes { + if node.ID == id { + return node, true + } + } + return models.Node{}, false +} + +func (ds *DataService) SearchNodes(query string) []models.Node { + ds.mutex.RLock() + defer ds.mutex.RUnlock() + + if query == "" { + return []models.Node{} + } + + searchLower := strings.ToLower(query) + var results []models.Node + + for _, node := range ds.data.Nodes { + labelMatch := strings.Contains(strings.ToLower(node.Label), searchLower) + idMatch := strings.Contains(strings.ToLower(node.ID), searchLower) + typeMatch := node.Type != "" && strings.Contains(strings.ToLower(node.Type), searchLower) + + if labelMatch || idMatch || typeMatch { + results = append(results, node) + } + } + + return results +} + +func (ds *DataService) GetNeighbors(nodeID string) (models.NeighborResponse, bool) { + ds.mutex.RLock() + defer ds.mutex.RUnlock() + + _, exists := ds.GetNodeByID(nodeID) + if !exists { + return models.NeighborResponse{}, false + } + + var neighborIDs []string + var relatedEdges []models.Edge + + for _, edge := range ds.data.Edges { + if edge.Source == nodeID { + neighborIDs = append(neighborIDs, edge.Target) + relatedEdges = append(relatedEdges, edge) + } else if edge.Target == nodeID { + neighborIDs = append(neighborIDs, edge.Source) + relatedEdges = append(relatedEdges, edge) + } + } + + var neighborNodes []models.Node + for _, node := range ds.data.Nodes { + for _, neighborID := range neighborIDs { + if node.ID == neighborID { + neighborNodes = append(neighborNodes, node) + break + } + } + } + + return models.NeighborResponse{ + Nodes: neighborNodes, + Edges: relatedEdges, + }, true +} + +func (ds *DataService) ReloadData() error { + return ds.loadData() +} + +func (ds *DataService) GetStats() map[string]int { + ds.mutex.RLock() + defer ds.mutex.RUnlock() + + typeCounts := make(map[string]int) + for _, node := range ds.data.Nodes { + if node.Type != "" { + typeCounts[node.Type]++ + } + } + + return map[string]int{ + "totalNodes": len(ds.data.Nodes), + "totalEdges": len(ds.data.Edges), + "conceptNodes": typeCounts["概念"], + "toolNodes": typeCounts["工具"], + "applicationNodes": typeCounts["应用"], + } +} diff --git a/frontend/src/services/graphApi.ts b/frontend/src/services/graphApi.ts index b006174..34cd349 100644 --- a/frontend/src/services/graphApi.ts +++ b/frontend/src/services/graphApi.ts @@ -1,7 +1,7 @@ import axios from 'axios'; import type { GraphData, Node, Edge } from '../types/graph'; -const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api'; +const API_BASE_URL = 'http://localhost:3001/api'; const apiClient = axios.create({ baseURL: API_BASE_URL,