golang web笔记-3.响应ResponseWriter

简介

从服务器向客户端返回响应需要使用 ResponseWriter,ResponseWriter是一个接口,handler用它来返回响应。

ResponseWriter常用方法

  1. Write:接收一个byte切片作为参数,然后把它写入到响应的body中。如果Write被调用时,header里边没有设定content type,那么数据的前512个字节就会被用来监测content type。

  2. Header:返回headers的map,可以进行修改,修改后的headers将会体现在返回给客户段的http响应里。

  3. WriteHeader: 方法接收一个整数类型作为参数,并把它设置为Http响应的状态吗,如果状态码没有被显示调用,默认WriteHeader(http.StatusOK);WriteHeader主要用来设置错误码。WriteHeader设置后Header将不能再被修改。

    Go 复制代码
    package main
    
    import (
    	"fmt"
    	"net/http"
    )
    
    func main() {
    	server := http.Server{
    		Addr: "localhost:8080",
    	}
    	http.HandleFunc("/test", func(writer http.ResponseWriter, request *http.Request) {
    		html := "<html><head><title>测试response</title></head><body><h1>Hello World!</h1></body></html>"
    		writer.Header().Set("Location", "http:localhost:8080")
    		writer.WriteHeader(302) //WriteHeader设置后Header将不能再被修改。修改header需要在设置WriteHeader之前
    		fmt.Fprintln(writer, "测试错误返回501")
    		writer.Write([]byte(html))
    	})
    	server.ListenAndServe()
    }

ResponseWriter返回json

创建json对应的struct

  1. 创建struct对应的实例
  2. 响应header的Content-Type需设置为appliation/json
  3. 使用json.Marshal将struct的实例转换为json
  4. 使用Write方法返回json
Go 复制代码
package main

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

type Post struct {
	User    string
	Threads []string
}

func main() {
	server := http.Server{
		Addr: "localhost:8080",
	}
	http.HandleFunc("/test", func(writer http.ResponseWriter, request *http.Request) {
		writer.Header().Set("Content-Type", "appliation/json")
		post := &Post{
			User:    "Xiaoqiang",
			Threads: []string{"first", "second", "third"},
		}
		jsonStr, _ := json.Marshal(post)
		writer.Write(jsonStr)

	})
	server.ListenAndServe()
}

内置响应

NotFound函数:返回404状态码和一个额外的信息

ServeFile函数:从文件系统提供文件返回给请求者

ServeContent函数:实现了io.ReadSeeker接口的任何东西里面的内容返回给请求者

Redirect函数:告诉客户段重定向到另外一个URl

相关推荐
LinXunFeng2 天前
Obsidian - 使用 Share Note 分享笔记并自部署
前端·笔记·github
LDR0067 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术7 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript
码云数智-园园7 天前
C++20 Modules 模块详解
java·开发语言·spring
swordbob7 天前
NIO的channel中什么是 fd(File Descriptor,文件描述符)
java·开发语言·nio
源分享7 天前
Java线程同步的多种实现方法(非常详细)
java·开发语言·jvm
Luminous.7 天前
C语言--day30
c语言·开发语言
何以解忧,唯有..7 天前
Go语言循环语句详解:for、range与循环控制
开发语言·算法·golang
謓泽7 天前
C语言不是语法,是通往机器的地图。
c语言·开发语言
云水一下7 天前
从零开始学 PHP 系列(一):PHP 的前世今生与开发环境搭建
开发语言·php