Golang发布首个简单项目 - yourbasic/graph的HTTP封装工具
Golang发布首个简单项目 - yourbasic/graph的HTTP封装工具 我计划在接下来的几周内继续改进。我可能几天内没有时间消化代码审查意见,但目前我可以收集任何评论。
graph-server
示例HTTP服务器,包装了一个图库
我正在将这个项目作为面试的作品集样本进行开发。我试图展示我对Golang基础有一定理解,并且接触过一些核心库。
我个人觉得图和图算法非常吸引人。
更多关于Golang发布首个简单项目 - yourbasic/graph的HTTP封装工具的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复
更多关于Golang发布首个简单项目 - yourbasic/graph的HTTP封装工具的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
这是一个很好的项目起点,展示了如何将核心算法库与HTTP服务封装结合。以下是一些针对yourbasic/graph库HTTP封装的实现要点和示例:
核心结构设计
package main
import (
"encoding/json"
"net/http"
"strconv"
"github.com/yourbasic/graph"
)
type GraphServer struct {
g *graph.Mutable
}
type EdgeRequest struct {
From int `json:"from"`
To int `json:"to"`
}
// 创建图实例
func NewGraphServer(vertices int) *GraphServer {
return &GraphServer{
g: graph.New(vertices),
}
}
HTTP端点示例
// 添加边
func (gs *GraphServer) AddEdge(w http.ResponseWriter, r *http.Request) {
var edge EdgeRequest
if err := json.NewDecoder(r.Body).Decode(&edge); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
gs.g.AddBoth(edge.From, edge.To)
w.WriteHeader(http.StatusCreated)
}
// 获取邻接节点
func (gs *GraphServer) GetNeighbors(w http.ResponseWriter, r *http.Request) {
vStr := r.URL.Query().Get("vertex")
vertex, err := strconv.Atoi(vStr)
if err != nil {
http.Error(w, "Invalid vertex", http.StatusBadRequest)
return
}
neighbors := gs.g.Neighbors(vertex)
json.NewEncoder(w).Encode(neighbors)
}
// 执行BFS搜索
func (gs *GraphServer) BFS(w http.ResponseWriter, r *http.Request) {
fromStr := r.URL.Query().Get("from")
toStr := r.URL.Query().Get("to")
from, err1 := strconv.Atoi(fromStr)
to, err2 := strconv.Atoi(toStr)
if err1 != nil || err2 != nil {
http.Error(w, "Invalid parameters", http.StatusBadRequest)
return
}
visited := graph.BFS(gs.g, from)
response := struct {
Reachable bool `json:"reachable"`
}{
Reachable: visited[to],
}
json.NewEncoder(w).Encode(response)
}
路由配置
func main() {
gs := NewGraphServer(100) // 初始化100个顶点
mux := http.NewServeMux()
mux.HandleFunc("/edge", gs.AddEdge)
mux.HandleFunc("/neighbors", gs.GetNeighbors)
mux.HandleFunc("/bfs", gs.BFS)
http.ListenAndServe(":8080", mux)
}
并发安全考虑
import "sync"
type SafeGraphServer struct {
mu sync.RWMutex
g *graph.Mutable
}
func (sgs *SafeGraphServer) SafeAddEdge(from, to int) {
sgs.mu.Lock()
defer sgs.mu.Unlock()
sgs.g.AddBoth(from, to)
}
func (sgs *SafeGraphServer) SafeNeighbors(vertex int) []int {
sgs.mu.RLock()
defer sgs.mu.RUnlock()
return sgs.g.Neighbors(vertex)
}
这个实现展示了:
- 图算法的HTTP接口封装
- RESTful端点设计
- 并发安全处理
- 错误处理机制
项目结构清晰,适合作为作品集展示Go语言在算法服务和HTTP开发方面的应用。

