go 开启一个 web 服务
package main
import (
"fmt"
"net/http"
)
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() {
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() {
http.HandleFunc("/hello", hello1)
http.ListenAndServe("localhost:8080", nil)
}
client
package main
import (
"fmt"
"io"
"net/http"
)
func main() {
response, _ := http.Get("http://www.baidu.com")
defer response.Body.Close()
data := make([]byte, 1024)
for {
n, err := response.Body.Read(data)
fmt.Println(n, err)
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】")
dbUserInfo := map[string]string{"username": "admin", "password": "123456"}
requestData := r.URL.Query()
username := requestData.Get("username")
password := requestData.Get("password")
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() {
requestUrl := "http://localhost:9999/login"
requestData := url.Values{}
requestData.Set("username", "admin")
requestData.Set("password", "123456")
urlUri, _ := url.ParseRequestURI(requestUrl)
urlUri.RawQuery = requestData.Encode()
res, _ := http.Get(urlUri.String())
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) {
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() {
http.HandleFunc("/register", register)
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 内部

【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步