Go Web --- 发送响应

  发送响应,不需要使用fmt包的各个API,只需要response的接口即可

package main
import (
	"net/http"
)
func index(response http.ResponseWriter, request *http.Request) {
	str := `<h1>hello world</h1>`

	//设置响应码
	//方法定义:WriteHeader(int)
	response.WriteHeader(200)

	//向返回的body中写数据
	//方法定义:Write([]byte) (int, error)
	response.Write([]byte(str))
}
func main() {
	server := http.Server{
		Addr: "127.0.0.1:8081",
	}
	http.HandleFunc("/index", index)
	server.ListenAndServe()
}

 

返回json数据

  明白一点:需要设置header,将Content-type设置为application/json

package main

import (
	"encoding/json"
	"net/http"
)

type Person struct {
	Name string
	Age  int
}

func index(response http.ResponseWriter, request *http.Request) {
	p := Person{"Jane", 30}
	data, _ := json.Marshal(p)
	response.WriteHeader(200)
	response.Header().Set("Content-Type", "application/json")
	response.Write(data)
}
func main() {
	server := http.Server{
		Addr: "127.0.0.1:8081",
	}
	http.HandleFunc("/index", index)
	server.ListenAndServe()
}

  

posted @ 2018-06-12 00:10  寻觅beyond  阅读(200)  评论(0)    收藏  举报
返回顶部