当前位置: 首页 > news >正文

GO 启动 简单服务

1.创建项目

  • 打开 GoLand -> 新建项目
  • 选择 “Go Modules (vgo)” 项目类型
  • 填写项目路径(如 examp
  • le.com/myapi)
  • 完成创建

2.创建 main.go 文件并添加以下代码

package mainimport ("encoding/json""fmt""log""net/http""time"
)// 定义一个响应结构体
type Response struct {Status  string      `json:"status"`Message string      `json:"message"`Data    interface{} `json:"data"`
}// 用户模型
type User struct {ID        int       `json:"id"`Name      string    `json:"name"`Email     string    `json:"email"`CreatedAt time.Time `json:"created_at"`
}// 用户数据存储(模拟数据库)
var users = []User{{ID: 1, Name: "张三", Email: "zhangsan@example.com", CreatedAt: time.Now()},{ID: 2, Name: "李四", Email: "lisi@example.com", CreatedAt: time.Now().Add(-24 * time.Hour)},
}func main() {// 设置路由http.HandleFunc("/", homeHandler)http.HandleFunc("/api/users", usersHandler)http.HandleFunc("/api/users/", userByIDHandler)// 启动服务器port := ":8080"fmt.Printf("🚀 服务器运行中,访问地址: http://localhost%s\n", port)fmt.Println("👉 可用端点:")fmt.Printf(" - GET http://localhost%s/api/users\n", port)fmt.Printf(" - GET http://localhost%s/api/users/:id\n", port)fmt.Println("=========================================")err := http.ListenAndServe(port, nil)if err != nil {log.Fatalf("❌ 启动服务器失败: %v", err)}
}// 主页处理器
func homeHandler(w http.ResponseWriter, r *http.Request) {if r.URL.Path != "/" {http.NotFound(w, r)return}response := Response{Status:  "success",Message: "欢迎使用用户API服务",Data:    "请访问 /api/users 获取用户数据",}sendJSON(w, http.StatusOK, response)
}// 获取所有用户
func usersHandler(w http.ResponseWriter, r *http.Request) {if r.Method != "GET" {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)return}response := Response{Status:  "success",Message: "用户数据获取成功",Data:    users,}sendJSON(w, http.StatusOK, response)
}// 按ID获取单个用户
func userByIDHandler(w http.ResponseWriter, r *http.Request) {if r.Method != "GET" {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)return}// 解析URL中的IDid := r.URL.Path[len("/api/users/"):]var userID int_, err := fmt.Sscanf(id, "%d", &userID)if err != nil {http.Error(w, "Invalid user ID", http.StatusBadRequest)return}// 查找用户var found *Userfor _, u := range users {if u.ID == userID {found = &ubreak}}// 返回响应if found == nil {response := Response{Status:  "error",Message: "用户未找到",Data:    nil,}sendJSON(w, http.StatusNotFound, response)return}response := Response{Status:  "success",Message: "用户数据获取成功",Data:    found,}sendJSON(w, http.StatusOK, response)
}// 发送JSON响应
func sendJSON(w http.ResponseWriter, statusCode int, data interface{}) {w.Header().Set("Content-Type", "application/json")w.WriteHeader(statusCode)if err := json.NewEncoder(w).Encode(data); err != nil {log.Printf("❌ JSON编码失败: %v", err)http.Error(w, "Internal Server Error", http.StatusInternalServerError)}
}

3.启动服务

终端中输入以下代码执行

go run main.go

或者
点击 main函数 旁边绿色启动按钮
在这里插入图片描述

在这里插入图片描述

4.模拟调用

创建 api_test.http 文件

### 获取所有用户
GET http://localhost:8080/api/users### 按ID获取用户 - 有效ID
GET http://localhost:8080/api/users/1### 按ID获取用户 - 无效ID
GET http://localhost:8080/api/users/999### 访问主页
GET http://localhost:8080/

点击绿色按钮调用
在这里插入图片描述
调用成功
在这里插入图片描述

http://www.dtcms.com/a/271984.html

相关文章:

  • 【YOLO脚本】yolo格式数据集删除缺失删除图片和标签
  • 青岛门卫事件后:高温晕厥救援技术突破
  • 文件系统----底层架构
  • 如何处理mocking is already registered in the current thread
  • IDEA 安装AI代码助手GitHub Copilot和简单使用体验
  • Apache http 强制 https
  • 百度文心ERNIE4.5部署与性能白皮书:FastDeploy加速方案+全系列模型实测数据对比
  • DVWA靶场通关笔记-弱会话IDs(Weak Session IDs Medium级别)
  • mmu 是什么?core和die是什么?
  • 计算机网络实验——无线局域网安全实验
  • UE 植物生长 Motion Design
  • 深度学习-正则化
  • 【SkyWalking】服务端部署与微服务无侵入接入实战指南
  • 【spring boot】三种日志系统对比:ELK、Loki+Grafana、Docker API
  • 【世纪龙科技】汽车信息化综合实训考核平台(机电方向)-学测
  • 零基础入门物联网-远程门禁开关:云平台创建
  • selenium中xpath的用法大全
  • anchor 智能合约案例5 之 vesting
  • 汽车加气站操作工历年考试真题及答案
  • CSS表达式——下篇【selenium】
  • WebSocket实战:实现实时聊天应用 - 双向通信技术详解
  • 【C++】——类和对象(上)
  • C 语言基础:操作符、进制与数据表示通俗讲解
  • AI【应用 03】Windows环境部署 TTS CosyVoice2.0 详细流程记录(Matcha-TTS、spk2info.pt等文件分享)
  • Qt中处理多个同类型对象共享槽函数应用
  • git多分支管理
  • 缺陷的生命周期(Bug Life Cycle)是什么?
  • Java 正则表达式白皮书:语法详解、工程实践与常用表达式库
  • WWDC 25 风云再起:SwiftUI 7 Charts 心法从 2D 到 3D 的华丽蜕变
  • 【HarmonyOS Next之旅】DevEco Studio使用指南(四十二) -> 动态修改编译配置