day17 网络编程

go 开启一个 web 服务

  • net 包,所有有关网络的都在net包下
package main

import (
	"fmt"
	"net/http"
)

// 需要传入 :ResponseWriter, *Request
func hello(rw http.ResponseWriter, request *http.Request) {
	fmt.Println("已经收到请求")
	fmt.Println("请求地址:", request.Host)
	fmt.Println("请求接口:", request.URL)
	fmt.Println("请求方法:", request.Method)

	// 响应
	rw.Write([]byte("hello go web!你好 go web"))
}
func main() {
	/* net 包 */
	/* 手动开启一个 http 的服务*/
	http.HandleFunc("/hello", hello)
	//
	http.ListenAndServe(":8080", nil)
}

普通Server/Client 通信

server
package main

import (
	"fmt"
	"net/http"
)

func hello1(response http.ResponseWriter, req *http.Request) {
	// - 请求
	fmt.Println("【request URL】:", req.URL)
	fmt.Println("【request Header】:", req.Header)
	fmt.Println("【request Host】:", req.Host)
	fmt.Println("【request Method】:", req.Method)
	// - 响应
	response.Write([]byte("<H1 style='color:red'>colorcolorcolor</H1>"))
}
func main() {
	/*
		go 中的所有网络相关的。都在net包下,http也在net包下
			- 包含 服务端 和 客户端
	*/

	// http  处理请求的方法
	http.HandleFunc("/hello", hello1)
	// 地址,处理器。 默认最后一行
	http.ListenAndServe("localhost:8080", nil)

}

client
package main

import (
	"fmt"
	"io"
	"net/http"
)

func main() {

	/* go 发送请求并获取响应 */

	//1.发送请求
	//response, _ := http.Get("http://localhost:8080/hello")
	response, _ := http.Get("http://www.baidu.com")
	//2.延时关闭 请求链接
	defer response.Body.Close()

	//3.循环 读取body里的数据
	data := make([]byte, 1024)
	for {
		n, err := response.Body.Read(data)
		fmt.Println(n, err)
		// 当 err 信息 :不等于nig 并且 不为 EOF 时表示还没读完
		if err != nil && err != io.EOF { // 没错误,继续读取,有错误另外处理
			fmt.Println(">>>>>>>读取时,产生其他错误:", err)
			return
		} else {
			fmt.Println("读取中!!!")
			fmt.Println(string(data[:n]))
			if n == 0 {
				fmt.Println("读取完毕!!!")
				break
			}
		}
	}

}

带参数Server/Client 通信

server
package main

import (
	"fmt"
	"net/http"
)

func login(w http.ResponseWriter, r *http.Request) {
	fmt.Println("【进入login】")

	// 1. 设置 模拟 db map数据
	dbUserInfo := map[string]string{"username": "admin", "password": "123456"}

	//2. 读取请求参数
	requestData := r.URL.Query()

	//3. 获取请求参数数据
	username := requestData.Get("username")
	password := requestData.Get("password")

	//4. 判断是否能够登陆
	if dbUserInfo["username"] == username && dbUserInfo["password"] == password {
		w.Write([]byte(`{"code":200,"data":{"username":"admin","password":"123456"}}`))

	} else {
		w.Write([]byte(`{"code":400,"data":{}}`))
	}

}
func main() {
	/* 模拟登陆 */

	http.HandleFunc("/login", login)
	http.ListenAndServe("localhost:9999", nil)
}

client
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
)

func main() {

	//1. 设置 请求地址
	requestUrl := "http://localhost:9999/login"

	//2. 封装参数 通过 http url包
	requestData := url.Values{}
	requestData.Set("username", "admin")
	requestData.Set("password", "123456")

	//3. 拼接参数到 请求地址上
	urlUri, _ := url.ParseRequestURI(requestUrl)
	urlUri.RawQuery = requestData.Encode()

	// 4. 发送请求
	res, _ := http.Get(urlUri.String())

	// 5. 处理请求结果
	responseData, _ := ioutil.ReadAll(res.Body)
	fmt.Println(res.StatusCode)
	fmt.Println(res.Header)
	fmt.Println(res.ContentLength)
	fmt.Println("请求结果:", string(responseData))

}

表单Server/Client 通信

server
package main

import (
	"fmt"
	"net/http"
)

func register(writer http.ResponseWriter, request *http.Request) {

	// 1. 获取表单数据
	request.ParseForm()             // 解析页面表单
	requestData := request.PostForm // 获取表单数据
	username := requestData.Get("username")
	password := requestData.Get("password")
	fmt.Println(">>>requestData", requestData)
	fmt.Println(">>>username", username, ">>>password", password)

	writer.Write([]byte("注册成功!"))

}

func main() {
	/* form 表单数据 提交到后台。 即 post 请求携带数据 */

	// 1. 注册处理函数
	http.HandleFunc("/register", register)
	// 2. 开启监听服务
	http.ListenAndServe(":8080", nil)
}

client
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<H1>注册表单</H1>
<form action="http://127.0.0.1:8080/register" method="post">
    <p>账户:<input type="text" name="username" id="username"></p>
    <p>密码:<input type="password" name="password" id="password"></p>
    <button type="submit">提交</button>
</form>

</body>
</html>

go 返回 template 模板 不常用,比python的模板还难用!!!

Server
package main

import (
	"fmt"
	"html/template"
	"net/http"
)

type User struct {
	username string
	age      int
	Name     string
}

func userFunc(w http.ResponseWriter, r *http.Request) {

	// 1. 组装 map嵌套结构体 数据
	userMap := make(map[int]User)
	userMap[0] = User{age: 18, username: "zhangsan", Name: "aaa"}
	userMap[1] = User{age: 22, username: "lisi", Name: "bbb"}
	// 2. 数据返回给模板
	templatePath := "userList.html"
	userListTemplate, err := template.ParseFiles(templatePath)
	if err != nil {

		fmt.Println("模板解析错误!!")
		return
	}
	templateData := make(map[string]map[int]User)
	templateData["data"] = userMap
	userListTemplate.Execute(w, templateData)

}
func main() {

	/* go 的template 使用 */

	// 1. 注册路由和函数
	http.HandleFunc("/user", userFunc)
	// 2. 开启监听服务
	http.ListenAndServe(":8080", nil)

}

Client
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!-- 不分离 给页面传输数据  -->
<p>{{.data}}</p>
{{range $k,$v:= .data}}
<p>ID:{{$k}}</p>
<br>
<p>userInfo:{{$v}}</p>
<br>

<p>判断</p>
    {{if eq $k 1}}
        <p>Name:{{.Name}}</p>
    <br>
    <!--小写的不可展示-->
        <p>username:{{.username}}</p>
    <br>
        <p>V:{{$v}}</p>
    {{end}}
{{end}}
</body>
</html>

request 内部

posted @ 2024-07-03 02:32  染指未来  阅读(1)  评论(0编辑  收藏  举报