1. 创建 HTTP 服务器

使用 Go 语言的 net/http 包可以轻松地创建一个 HTTP 服务器。以下是一个简单的例子:

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, World!")
    })

    http.ListenAndServe(":8080", nil)
}

这个程序创建了一个简单的 HTTP 服务器,对于任意请求,它都会回复 "Hello, World!"。

  1. 处理表单提交

下面的示例演示了如何处理 HTML 表单的提交。它将表单数据解析为 Go 语言结构体,并将其打印到控制台上:

package main

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

type User struct {
    Name string
    Age  int
}

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        if r.Method == "GET" {
            t, err := template.ParseFiles("form.html")
            if err != nil {
                log.Println("Error parsing template:", err)
                return
            }
            t.Execute(w, nil)
        } else {
            name := r.FormValue("name")
            age := r.FormValue("age")

            user := User{Name: name, Age: age}

            fmt.Println(user)
            fmt.Fprintf(w, "Name: %s\nAge: %s", user.Name, user.Age)
        }
    })

    http.ListenAndServe(":8080", nil)
}

这个程序根据请求方法的不同分别进行处理。如果是 GET 请求,它将渲染一个包含表单的 HTML 页面。如果是 POST 请求,它将解析表单数据并将其打印到控制台上。

  1. 处理静态文件

在 web 应用程序中,通常需要为浏览器提供一些静态文件,如 CSS、JavaScript 和图像。使用 net/http 包,您可以轻松地为这些文件提供服务。

以下是一个简单的示例,演示了如何为静态文件提供服务:

package main

import (
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, r.URL.Path[1:])
    })

    log.Fatal(http.ListenAndServe(":8080", nil))
}

这个程序将为根 URL 和所有其他 URL 提供静态文件服务。如果浏览器请求 "/style.css",它将在当前目录中查找名为 "style.css" 的文件并将其发送到浏览器。

golang nethttp学习实操

原文地址: https://www.cveoy.top/t/topic/Cxy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录