开放的编程资料库

当前位置:我爱分享网 > Go教程 > 正文

如何在Go中设置HTTP服务器

GoHTTP静态文件教程展示了如何在Go中设置HTTP服务器以提供静态文件。

$ go version
go version go1.18.1 linux/amd64

我们使用Go版本1.18。

超文本传输​​协议(HTTP)是分布式协作超媒体信息系统的应用协议。HTTP协议是万维网数据通信的基础。

net/http包提供HTTP客户端和服务器实现,用于创建GET和POST请求。

静态文件是不会改变的文件。它们包括CSS文件、JavaScript文件和图像;也包括不包含模板指令的纯HTML文件。

http.FileServer用于提供静态文件。它返回一个处理程序,该处理程序使用文件系统的内容为HTTP请求提供服务。

提供静态文件

在第一个示例中,我们提供包含图像和CSS文件的HTML文件。

go.mod
main.go
public
├── about.html
├── css
│   └── format.css
├── img
│   └── sid.png
└── index.html

这是项目结构。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/format.css">
    <title>About</title>
</head>
<body>

    <h2>About page</h2>

    <p>
        <a href="/">Home page</a>
    </p>
    
</body>
</html>

这是about.html文件。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/format.css">
    <title>Home page</title>
</head>

<body>

    <h2>Home page</h2>

    <p>
        <a href="about.html">About page</a>
    </p>

    <figure>
        <img src="img/sid.png" alt="Sid the sloth">
        <figcaption>Sid the sloth</figcaption>
    </figure>

</body>

</html>

这是index.html页面。

* {
    font-size: medium;
    background-color:#2c2b2b ;
    color: #e6d7d7;
}

这是CSS文件。

package main

import (
    "net/http"
)

func main() {

    fs := http.FileServer(http.Dir("./public"))
    http.Handle("/", fs)

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

我们设置了服务器。从public目录中读取静态文件。

Go服务图像示例

在下面的示例中,我们使用模板文件动态生成页面。沿着模板系统,我们为包含在模板文件中的CSS文件设置服务静态文件。

go.mod
main.go
public
└── css
    └── format.css
templates
└── layout.html

这是项目结构。

table {
    border-top: 1px solid #999;
    border-left: 1px solid #999;
    border-collapse: collapse;
}

td, th {
    padding: 5px;
    border-right: 1px solid #999;
    border-bottom: 1px solid #999;
}

tr:nth-child(2) {
    background-color: #c1f5f7;
}

我们有一些CSS代码来设置HTML表格的样式。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="public/css/format.css">
    <title>Users</title>
</head>

<body>

    <table>
        <thead>
            <tr>
                <th>User</th>
                <th>Occupation</th>
            </tr>
        </thead>

        <tbody>
            {{ range . }}
            <tr>
                <td>{{ .Name }}</td>
                <td>{{ .Occupation }}</td>
            </tr>
            {{ end }}
        </tbody>
    </table>

</body>

</html>

在模板文件中,我们有指令将传递的数据合并到HTML表中。format.css文件包含在模板中并用作静态资源。

package main

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

type User struct {
    Name       string
    Occupation string
}

func main() {

    fs := http.FileServer(http.Dir("public"))
    http.Handle("/public/", http.StripPrefix("/public/", fs))

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

        tmpl := template.Must(template.ParseFiles("templates/layout.html"))

        data := []User{
            {Name: "John Doe", Occupation: "gardener"},
            {Name: "Roger Roe", Occupation: "driver"},
            {Name: "Thomas Green", Occupation: "teacher"},
        }

        tmpl.Execute(w, data)
    })

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

在代码示例中,我们设置了服务静态文件和模板引擎。

fs := http.FileServer(http.Dir("public"))
http.Handle("/public/", http.StripPrefix("/public/", fs))

静态资源来自public目录。

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

    tmpl := template.Must(template.ParseFiles("templates/layout.html"))

    data := []User{
        {Name: "John Doe", Occupation: "gardener"},
        {Name: "Roger Roe", Occupation: "driver"},
        {Name: "Thomas Green", Occupation: "teacher"},
    }

    tmpl.Execute(w, data)
})

public目录之外的所有资源都由模板引擎管理。在匿名函数中,我们使用template.parseFiles解析layout.html文件,并将其与数据合并。

在本教程中,我们展示了如何在Golang中使用静态资源。

列出所有Go教程。

未经允许不得转载:我爱分享网 » 如何在Go中设置HTTP服务器

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏