使用 go 设置 Web 服务器



我并不期望为我编写代码,我只是想朝着正确的方向推动。

我有一个任务是制作一个侦听端口 8080 的 Web 服务器,在此服务器上,我将呈现人类可读的数据。访问此服务器的人将使用/1、/2、/3 等访问这些路径。要呈现的数据将从 5 个不同的 API 收集,所有这些都将以 JSON 格式返回数据。

此外,所有路径都将使用 Go 模板呈现给该人。

一个人该怎么做呢?我可能听起来像是在布置家庭作业,但我真的很陌生,需要一些帮助。

在学习做同样的事情时,我发现以下内容非常有帮助:

  • https://golang.org/doc/articles/wiki/

    一个关于使用 net/http 包创建一个简单的基于 html 的 Web 应用程序的好教程。该包可用于从您使用的 API 收集信息以及发送响应 json。它引入了 html 模板,但 json 模板的过程基本没有变化。

  • https://medium.com/@IndianGuru/understanding-go-s-template-package-c5307758fab0

    Go 模板引擎概述。

  • https://blog.golang.org/json-and-go

    一篇关于使用 go 在 JSON 中编码(封送(和解码(解封(数据的博客文章。

您将从答案中获得大量资源。我想给出一些简单的代码,您可以测试它是否符合您的需求:

有一个简单的文件夹结构,如下所示:

ProjectName
├── main.go
└── templates
    └── index.html

main.go内部,我们创建了一个侦听端口 8080 的 http 服务器。以下是注释的整个代码:

main.go

package main
import (
    "encoding/json"
    "fmt"
    "html/template"
    "io/ioutil"
    "net/http"
)
// User information of a GitHub user. This is the
// structure of the JSON data you are rendering so you
// customize or make other structs that are inline with
// the API responses for the data you are displaying
type User struct {
    Name     string `json:"name"`
    Company  string `json:"company"`
    Location string `json:"location"`
    Email    string `json:"email"`
}
func main() {
    templates := template.Must(template.ParseFiles("templates/index.html"))
    // The endpoint
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        user, err := getGithubUser("musale")
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
        }
        if err := templates.ExecuteTemplate(w, "index.html", user); err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
        }
    })
    // Start the server on 8080
    fmt.Println(http.ListenAndServe(":8080", nil))
}
// One of your API endpoints
func getGithubUser(username string) (User, error) {
    var resp *http.Response
    var err error
    var user User
    // The endpoint
    const githubUserAPI = "https://api.github.com/users/"
    // Get the required data in json
    if resp, err = http.Get(githubUserAPI + username); err != nil {
        return user, err
    }
    defer resp.Body.Close()
    var body []byte
    if body, err = ioutil.ReadAll(resp.Body); err != nil {
        return user, err
    }
    // Unmarshal the response into the struct
    if err = json.Unmarshal(body, &user); err != nil {
        return user, err
    }
    return user, nil
}

然后在index.html中只需使用:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Github User</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <p>Name: {{.Name}}</p>
    <p>Company: {{.Company}}</p>
    <p>Location: {{.Location}}</p>
    <p>Email: {{.Email}}</p>
</body>
</html>

大多数资源都解决了代码片段,通过更多的修改,您将能够将参数传递到 URL 中,根据路由等呈现数据。我希望这能让您了解如何轻松解决问题。祝你好运!

最新更新