首页 > 学院 > 开发设计 > 正文

Golang API 类型 Get

2019-11-10 20:21:06
字体:
来源:转载
供稿:网友

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


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表