package mainimport ( "encoding/json" "fmt" "net/http" "strconv" . "github.com/soekchl/myUtils")type Student struct { Id int Name string phone string // 不顯示}var ( students []Student)func main() { students = append(students, Student{Id: 1, Name: "Luke1"}) students = append(students, Student{Id: 2, Name: "Luke2"}) students = append(students, Student{Id: 3, Name: "Luke3"}) students = append(students, Student{Id: 4, Name: "Luke4"}) students = append(students, Student{Id: 5, Name: "Luke5"}) students = append(students, Student{Id: 6, Name: "Luke6"}) http.HandleFunc("/", get) Notice("開始監聽:8080端口") if err := http.ListenAndServe(":8088", nil); err != nil { Error("接口服務器開啟失敗!", err) }}func get(w http.ResponseWriter, r *http.Request) { limit, _ := strconv.Atoi(r.FormValue("limit")) if limit < 1 || limit > len(students) { limit = len(students) } data, err := json.Marshal(students[:limit]) if err != nil { Error("數據解析錯誤!", err) fmt.FPRintf(w, "數據解析錯誤!") return } fmt.Fprintf(w, string(data))}監聽 8088 端口 調用 http://localhost:8088/?limit=3
新聞熱點
疑難解答