test go server
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// User 结构体,用于返回 JSON 数据
|
||||
type User struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// 根路径处理器
|
||||
func homeHandler(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprintf(w, "Hello, World! 👋")
|
||||
}
|
||||
|
||||
// /time 路径处理器,返回当前服务器时间
|
||||
func timeHandler(w http.ResponseWriter, r *http.Request) {
|
||||
currentTime := time.Now().Format("2006-01-02 15:04:05")
|
||||
fmt.Fprintf(w, "当前服务器时间: %s", currentTime)
|
||||
}
|
||||
|
||||
// /api/user 路径处理器,返回 JSON 数据
|
||||
func userHandler(w http.ResponseWriter, r *http.Request) {
|
||||
user := User{
|
||||
ID: 1,
|
||||
Name: "张三",
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(user)
|
||||
}
|
||||
|
||||
// 带请求参数处理的处理器
|
||||
func helloHandler(w http.ResponseWriter, r *http.Request) {
|
||||
name := r.URL.Query().Get("name")
|
||||
if name == "" {
|
||||
name = "World"
|
||||
}
|
||||
fmt.Fprintf(w, "Hello, %s!", name)
|
||||
}
|
||||
|
||||
func main() {
|
||||
// 注册路由
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/", homeHandler)
|
||||
mux.HandleFunc("/time", timeHandler)
|
||||
mux.HandleFunc("/api/user", userHandler)
|
||||
mux.HandleFunc("/hello", helloHandler)
|
||||
|
||||
// 启动 HTTP 服务
|
||||
addr := ":8080"
|
||||
log.Printf("启动 HTTP 服务,监听端口 %s\n", addr)
|
||||
if err := http.ListenAndServe(addr, mux); err != nil {
|
||||
log.Fatalf("服务器启动失败: %v", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user