net/http包的简单使用

89 阅读1分钟

部分实例

// Functions that handle user requests
func handlerFunc(w http.ResponseWriter, r *http.Request) {
   // 设置响应头
   w.Header().Set("X-APP-NAME", "GoBlog")
   w.Header().Set("X-APP-CREATOR", "Tacks")
   // 设置响应状态码
   w.WriteHeader(http.StatusOK)
   // 设置响应主体body
   fmt.Fprintf(w, "<h1>Hi! This my GoBlog, I am Tacks! </h1>")
   fmt.Fprintf(w, "<h2>User Request</h2>")
   // 获取用户请求的host并且返回
   fmt.Fprintf(w, "[Host]: " + r.Host + "<br>")
   // 获取用户的浏览器标志并且返回
   fmt.Fprintf(w, "[User-Agent]: " + r.Header.Get("User-Agent") + "<br>")
   // 采用Write输出内容
   w.Write([]byte("=> to be continue ... "))
}

精彩文章推荐:

net/http包使用模式

Go Web 编程

字节开源WEB框架Hertz太香啦