使用go设置Web服务器

时间:2018-04-19 13:07:56

标签: go

我不希望得到为我编写的代码,我只想在正确的方向上轻推。

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

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

怎么会这样做呢? 我可能听起来像是在做作业,但我真的很陌生,需要一些帮助。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

有一个像这样的简单文件夹结构:

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>

大多数资源都会解决代码片段,并且需要更多修改,您可以将params传递到URL中,根据路径等呈现数据。我希望这能让您了解如何轻松解决你的问题。祝你好运!

相关问题