一、项目简介:
实现一个简单的web服务器,通过浏览器访问不同的请求地址,展示不同的内容。下面是最终效果图:
1、浏览器访问 localhost:8080/
2、浏览器访问 localhost:8080/hello
3、浏览器访问 localhost:8080/form.html,填写内容后点击提交
二、具体实现
1. 创建项目
- 创建一个文件夹go-server
- 在go-server目录下,创建一个static文件夹
- 在static目录下创建index.html和form.html
- 分别写入以下代码
index.html
<html>
<head>
<title>
Static Website
</title>
</head>
<body>
<h2>Static Website</h2>
</body>
</html>
form.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>
<form action="/form" method="POST">
<label>Name</label><input type="text" name="name" value=""/>
<label>Address</label><input type="text" name="address" value=""/>
<input type="submit" />
</form>
</div>
</body>
</html>
- 在go-server目录下创建main.go文件,整个目录结构如下:
2.main函数实现
func main() {
//创建一个文件服务器,会去static目录下找index.html
fileServer := http.FileServer(http.Dir("./static"))
// 将 "/" 路径映射到文件服务器
http.Handle("/", fileServer)
// 定义 "/hello" 路径的处理器
http.HandleFunc("/hello", HelloHandler)
// 定义 "/form" 路径的处理器
http.HandleFunc("/form", FormHandler)
fmt.Printf("Starting server at port 8080\n")
// 启动HTTP服务器并监听端口 8080,如果出现错误,则打印错误信息并退出
if err := http.ListenAndServe("localhost:8080", nil); err != nil {
log.Fatal(err)
}
}
3.HelloHandler实现
处理/hello路径的请求,返回’hello’字符串
func HelloHandler(w http.ResponseWriter, r *http.Request) {
//判断请求路径是否正确
if r.URL.Path != "/hello" {
http.Error(w, "404 not found", http.StatusNotFound)
return
}
//判断请求方式是否正确
if r.Method != "GET" {
http.Error(w, "method is not supported", http.StatusNotFound)
return
}
fmt.Fprintf(w, "hello!")
}
4.FormHandler实现
处理/form
路径的请求,将表单数据解析并打印出来
注意:直接在浏览器输入 localhost:8080/form 这个路径是不行的,会返回method is not supported.这是因为浏览器默认是发送get请求的,而这表单的请求是需要post请求才可以。
需要先输入localhost:8080/form.html访问页面,然后填入数据后,点击提交按钮,会发送post请求到/form路径。
func FormHandler(w http.ResponseWriter, r *http.Request) {
//判断请求路径是否正确
if r.URL.Path != "/form" {
http.Error(w, "404 not found", http.StatusNotFound)
return
}
//判断请求方式是否正确
if r.Method != "POST" {
http.Error(w, "method is not supported", http.StatusNotFound)
return
}
//解析表单数据是否正确
if err := r.ParseForm(); err != nil {
fmt.Fprintf(w, "ParseForm() err: %v", err)
return
}
fmt.Fprintf(w, "POST request successful\n")
name := r.FormValue("name")
address := r.FormValue("address")
fmt.Fprintf(w, "name is:%s\n", name)
fmt.Fprintf(w, "address is: %s", address)
}
5.完整代码
package main
import (
"fmt"
"log"
"net/http"
)
func HelloHandler(w http.ResponseWriter, r *http.Request) {
//判断请求路径是否正确
if r.URL.Path != "/hello" {
http.Error(w, "404 not found", http.StatusNotFound)
return
}
//判断请求方式是否正确
if r.Method != "GET" {
http.Error(w, "method is not supported", http.StatusNotFound)
return
}
fmt.Fprintf(w, "hello!")
}
func FormHandler(w http.ResponseWriter, r *http.Request) {
//判断请求路径是否正确
if r.URL.Path != "/form" {
http.Error(w, "404 not found", http.StatusNotFound)
return
}
//判断请求方式是否正确
if r.Method != "POST" {
http.Error(w, "method is not supported", http.StatusNotFound)
return
}
//解析表单数据是否正确
if err := r.ParseForm(); err != nil {
fmt.Fprintf(w, "ParseForm() err: %v", err)
return
}
fmt.Fprintf(w, "POST request successful\n")
name := r.FormValue("name")
address := r.FormValue("address")
fmt.Fprintf(w, "name is:%s\n", name)
fmt.Fprintf(w, "address is: %s", address)
}
func main() {
//创建一个文件服务器,会去static目录下找index.html
fileServer := http.FileServer(http.Dir("./static"))
// 将 "/" 路径映射到文件服务器
http.Handle("/", fileServer)
// 定义 "/hello" 路径的处理器
http.HandleFunc("/hello", HelloHandler)
// 定义 "/form" 路径的处理器
http.HandleFunc("/form", FormHandler)
fmt.Printf("Starting server at port 8080\n")
// 启动HTTP服务器并监听端口 8080,如果出现错误,则打印错误信息并退出
if err := http.ListenAndServe("localhost:8080", nil); err != nil {
log.Fatal(err)
}
}