package main import ( "encoding/json" "net/http" ) func main() { // 演示地址:http://localhost:8080/demo.html http.HandleFunc("/demo.html", func(writer http.ResponseWriter, request *http.Request) { // 数据 data := map[string]any{} data["errcode"] = 40029 data["errmsg"] = "invalid code" // 设置响应头的Content-Type为application/json,否则默认为text/plain writer.Header().Set("Content-Type", "application/json; charset=utf-8") // 设置自定义内容 writer.Header().Set("X-AspNetMvc-Version", "4.0") writer.Header().Set("X-AspNet-Version", "4.0.30319") writer.Header().Set("X-Powered-By", "ASP.NET") // map转为json jsonByte, _ := json.Marshal(data) // 在页面输出json字符串 _, _ = writer.Write(jsonByte) }) // 启动HTTP服务器 err := http.ListenAndServe(":8080", nil) if err != nil { panic("启动HTTP服务器失败") } }
Copyright © 2024 码农人生. All Rights Reserved