http模块-监听、请求处理
Go语言之下,所有的跟网络相关的都在net包下
我们在使用http有两件事情:
1.有用户请求的时候如何处理
2.监听的是哪个端口
监听:告诉操作系统,某个端口是由当前程序处理的
https://是协议部分
//后面的部分是host主机域名
/后面的是请求的路径
http 端口号:80
https 端口号:443
package main
import (
"net/http"
)
func main(){
//1.处理请求 HandleFunc:注册一个处理函数
//第1个参数:用户请求的地址
//第2个参数的函数是有参数的
http.HandleFunc("/", func (
w http.ResponseWriter,//给前台发送响应
req *http.Request,//Request:前台请求了什么的信息
){
})
//2.监听,准备开始服务,监听80号端口 监听参数:nil
http.ListenAndServe(":80", nil)
}
服务器就开起来了
本地的服务器的域名:localhost
为什么是白的?因为我们刚才写的服务器没有结果返回
localhost默认访问80端口,如果服务器不是80端口,则要自己添加:端口号
http模块-数据响应、请求信息
能用于操作文件的方法都适用于操作w http.ResponseWriter
Fprintf向指定的writer打印
我们还可以处理图片:
package main
import (
"net/http"
"io/ioutil"
"encoding/json"
// "fmt"
)
func main(){
//1.处理请求
http.HandleFunc("/", func (
w http.ResponseWriter,
req *http.Request,
){
// fmt.Fprintf(w, "aaa %d", 12)
// w.Write([]byte("dasdfasdf"))
data,err:=ioutil.ReadFile("./a.png")
if err!=nil {panic(err)}
w.Write(data)
})
//2.监听
http.ListenAndServe(":80", nil)
}
然后跳到localhost,图片就出来了
发送响应的总结
发送响应:
1.字符串
w.Write([]byte("dfasdfdas"))
2.动态字符串
fmt.Fprintf(w, "xxxx", x, x)
3.二进制(例如:文件)
data=ioutil.Read(xxx)
w.Write(data)
4.json
json.NewEncoder(w).Encode(map/struct)
json的使用方法如下:
package main
import (
"net/http"
"encoding/json"
)
func main(){
//1.处理请求
http.HandleFunc("/", func (
w http.ResponseWriter,
req *http.Request,
){
json.NewEncoder(w).Encode(map[string]string{
"name": "blue",
"gender": "male",
})
})
//2.监听
http.ListenAndServe(":80", nil)
}
req—请求信息
package main
import (
"net/http"
)
func main(){
//1.处理请求
http.HandleFunc("/", func (
w http.ResponseWriter,
req *http.Request,
){
w.Write([]byte("aaa"))
})
//2.监听
http.ListenAndServe(":80", nil)
}
我们现在的这个路径:/ 是向后匹配,只要开头是/的,都可以匹配
如果我们要特定的某一个,我们就要/往后加
我们需要路由,精确匹配