GO语言项目实战【一】——实现一个简单的WEB服务器

本文详细介绍了如何使用Go语言创建一个基础的Web服务器,包括静态文件服务、不同路径的处理器(如/hello和/form)以及表单数据的POST请求处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、项目简介:

实现一个简单的web服务器,通过浏览器访问不同的请求地址,展示不同的内容。下面是最终效果图:
1、浏览器访问 localhost:8080/

image.png
2、浏览器访问 localhost:8080/hello

image.png

3、浏览器访问 localhost:8080/form.html,填写内容后点击提交

image.png

image.png

二、具体实现

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文件,整个目录结构如下:

image.png

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)
   }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值