go语言学习第六天==>处理http请求、设置http详细信息、服务器响应JSON数据(可给ajax解析)、json+map+struct之间的转换
- HTTP服务端处理HTTP请求
//函数原型:指定tcp地址 进行监听
//参数1为地址
//参数2为服务端处理程序 通常为空
func ListenAndServe(addr string, handler Handler) error
//指定路径和请求处理函数 如
http.Handle("/foo", fooHandler)
demo 注册8888端口进行监听
package main
import "net/http"
import "fmt"
import "log"
func checkInfo(w http.ResponseWriter,r *http.Request){
if r.Method == "GET" {
w.Write([]byte("my first go server"))
//获取请求参数列表
vars := r.URL.Query();
fmt.Println(vars.Get("name"))
fmt.Println(vars["name"])
}
}
func main() {
http.HandleFunc("/test",checkInfo)
//log.Fatal() 输出错误信息
log.Fatal(http.ListenAndServe("127.0.0.1:8888",nil))
//也可以直接 :http.ListenAndServe("127.0.0.1:8888",nil)
}
// 在地址输入:http://127.0.0.1:8888/test?name=value
demo设置详细信息
package main
import "net/http"
import "fmt"
import "log"
import "time"
func checkInfo(w http.ResponseWriter,r *http.Request){
w.Write([]byte("my first go server"))
vars := r.URL.Query();
fmt.Println(vars.Get("name"))
fmt.Println(vars["name"])
}
func main() {
// log.Fatal() 输出日志信息
/*
http.HandleFunc("/test",checkInfo)
log.Fatal(http.ListenAndServe("127.0.0.1:8888",nil))
*/
/
///方法二:给服务器设置详细信息
http.HandleFunc("/test",checkInfo)
s := &http.Server{
Addr: "127.0.0.1:8888",
// Handler: checkInfo,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
log.Fatal(s.ListenAndServe())
}
// 在地址输入:http://127.0.0.1:8888/test?name=value
demo 服务器端相应JSON,设置允许跨域来源请求
注:结构体内的成员变量首字母大写
package main
import "net/http"
import "fmt"
import "log"
import "encoding/json"
//注:一定要首字母大写否则 转化的JSON为空(小写字母开头为不可见)
type people struct {
Name []string
Age string
Height float32
}
func checkInfo(w http.ResponseWriter,r *http.Request){
if origin := r.Header.Get("Origin"); origin != "" {
//*号表示允许所有来源跨域端访问
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers","Action, Module") //有使用自定义头 需要这个,Action, Module是例子
}
// 创建并初始化结构体变量
one := people{
[]string{"kongyu","kongyu01"},
"ssssss",
52.0,
}
// 或者
/*
one := people{
Name: []string{"kongyu","kongyu01"},
Age: "ssssss",
Height: 52.0,
}
*/
//结构体转化为json数据 map转json也是用此方法 json.Marshal(map)
b, err := json.Marshal(one)
// b, err := json.MarshalIndent(one, "", " ") //->格式化json
if err != nil {
fmt.Println("Umarshal failed:", err)
}
fmt.Println(string(b))
//w.Header().Set("Content-Type", "text/html") 这样写浏览器将会把返回的数据以HTML方式渲染
// 返回JSON数据体(可被ajax解析)
w.Header().Set("Content-Type", "application/json")
w.Write(b)
}
func main() {
// 注册路径以及监听函数
http.HandleFunc("/test",checkInfo)
// log.Fatal() 输出日志信息
//
log.Fatal(http.ListenAndServe("127.0.0.1:8888",nil))
}
// 在地址输入:http://127.0.0.1:8888/test
demo json数据转换为map/结构体
package main
import "net/http"
import "fmt"
import "log"
import "encoding/json"
//注:一定要首字母大写否则 转化的JSON为空(小写字母开头为不可见)
type people struct {
Name []string
Age string
Height float32
}
func checkInfo(w http.ResponseWriter,r *http.Request){
if origin := r.Header.Get("Origin"); origin != "" {
//*号表示允许所有来源跨域端访问
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers","Action, Module") //有使用自定义头 需要这个,Action, Module是例子
}
// 创建并初始化结构体变量
one := people{
[]string{"kongyu","kongyu01"},
"ssssss",
52.0,
}
// 或
/*
one := people{
Name: []string{"kongyu","kongyu01"},
Age: "ssssss",
Height: 52.0,
}
*/
//结构体转化为json数据 map转json也是Marshal(map)
b, err := json.Marshal(one)
// b, err := json.MarshalIndent(one, "", " ") //->格式化json
if err != nil {
fmt.Println("Umarshal failed:", err)
}
fmt.Println(string(b))
///
///json转结构体
/
jsonBuf:=`
{
"name":[
"kong",
"yu"
],
"Height":52.0,
"Age":"|i do not konw|",
"more":"eeeeee"
}`
jsonBuf2:=`
{
"Age":"onlyOne"
}`
var peo people
var peo1 people
var peo2 people
e := json.Unmarshal([]byte(b), &peo)
//json数据大于结构体数据
json.Unmarshal([]byte(jsonBuf), &peo1)
//json数据小于结构体数据
json.Unmarshal([]byte(jsonBuf2), &peo2)
if e==nil {
fmt.Println("我要输出people信息了")
fmt.Println(peo)
fmt.Println(peo1)
fmt.Println(peo2)
}
///json转map
//
m1 := make(map[string]interface{}, 2)
m2 := make(map[string]interface{})
json.Unmarshal([]byte(jsonBuf), &m1)
json.Unmarshal([]byte(jsonBuf), &m2)
fmt.Println("我要输出map信息了")
fmt.Println(m1)
fmt.Println(m2)
// 返回JSON数据体(可被ajax解析)
w.Header().Set("Content-Type", "application/json")
w.Write(b)
}
func main() {
// 注册路径以及监听函数
http.HandleFunc("/test",checkInfo)
// log.Fatal() 输出日志信息
//
log.Fatal(http.ListenAndServe("127.0.0.1:8888",nil))
}
// 在地址输入:http://127.0.0.1:8888/test
总结:
1 json数据条数大于等于还是小于结构体成员数都可以转换
2 没有得到值的结构体成员默认为零值
3 转换为map时,和map的溶解无关 map转为json时map的key值必须是string