GO 启动 简单服务

1.创建项目

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

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

go 复制代码
package main

import (
	"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中的ID
	id := 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 *User
	for _, u := range users {
		if u.ID == userID {
			found = &u
			break
		}
	}

	// 返回响应
	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.启动服务

终端中输入以下代码执行

bash 复制代码
go run main.go

或者

点击 main函数 旁边绿色启动按钮

4.模拟调用

创建 api_test.http 文件

bash 复制代码
### 获取所有用户
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/

点击绿色按钮调用

调用成功

相关推荐
超级架构师18 分钟前
PRAXO-CORE 2.5.0:用 conformance 和显式边界构建 Go Agent 框架
开发语言·人工智能·后端·golang·ai编程·智能体框架·praxo-core
陈随易36 分钟前
AI 运维服务器,安全又可靠的方法
前端·后端·程序员
叼烟扛炮1 小时前
Linux 学习笔记(四十三):网络编程进阶——自定义协议解决 TCP 粘包与守护进程
linux·开发语言·网络·笔记·tcp/ip
LMT流氓兔2 小时前
第五单元——第十六课:给书店助手加上网页界面
java·开发语言·jvm·人工智能·oracle·langchain·1024程序员节
专注仿真2 小时前
梯度提升类(XFBoost)算法详解与代码实例
开发语言·人工智能·python·算法·大模型训练·控制算法
外收内放2 小时前
Python基础语法练习题(75)
开发语言·python·学习
IT_陈寒2 小时前
JavaScript的this坑人实录,这次我真的记下来了
前端·人工智能·后端
starzy19903 小时前
Scala循环与判断:一切皆表达式的控制流
开发语言·人工智能·scala
starzy19903 小时前
Scala类和对象:从构造器到样例类的完整指南
开发语言·后端·scala
梦影_3 小时前
MySQL进阶教程(五)—— SQL调优(下)
android·大数据·数据库·后端·sql·mysql·database