使用go设置Web服务器 [英] Setting up a web server using go

查看:48
本文介绍了使用go设置Web服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不希望为我编写代码,我只是想朝着正确的方向前进.

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

所有路径均应使用Go模板呈现给人员.

人们将如何去做呢?听起来好像我正在分发作业,但是我对此确实很陌生,需要一些帮助.

解决方案

答案中将有很多资源.我想给出一些简单的代码,您可以测试它们是否符合您的需求:

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

  ProjectName├──main.go└──模板└──index.html 

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

main.go

 程序包主要进口 (编码/json""fmt""html/模板""io/ioutil""net/http")//GitHub用户的用户信息.这是//您要呈现的JSON数据的结构//自定义或制作与之内联的其他结构//您显示的数据的API响应键入User struct {名称字符串`json:"name"`公司字符串`json:"company"`位置字符串`json:"location"`电子邮件字符串`json:"email"`}func main(){模板:= template.Must(template.ParseFiles("templates/index.html"))//端点http.HandleFunc("/",func(w http.ResponseWriter,r * http.Request){用户,错误:= getGithubUser("musale")如果err!= nil {http.Error(w,err.Error(),http.StatusInternalServerError)}如果err:= templates.ExecuteTemplate(w,"index.html",用户);err!= nil {http.Error(w,err.Error(),http.StatusInternalServerError)}})//在8080上启动服务器fmt.Println(http.ListenAndServe(:8080",nil))}//您的API端点之一func getGithubUser(用户名字符串)(用户,错误){var resp * http.Responsevar err错误var user用户//端点const githubUserAPI ="https://api.github.com/users/"//在json中获取所需的数据如果是resp,err = http.Get(githubUserAPI +用户名);err!= nil {返回用户,错误}延迟resp.Body.Close()var body [] byte如果是正文,则err = ioutil.ReadAll(resp.Body);err!= nil {返回用户,错误}//将响应解组到结构中如果err = json.Unmarshal(body,& user);err!= nil {返回用户,错误}返回用户,无} 

然后在 index.html 中使用:

 <!DOCTYPE html>< html>< head>< meta charset ="utf-8"/>< meta http-equiv ="X-UA-Compatible" content ="IE = edge">< title> Github用户</title>< meta name ="viewport" content ="width = device-width,initial-scale = 1"></head><身体>< p>名称:{{.Name}}</p>< p>公司:{{.Company}}</p>< p>位置:{{.Location}}</p>< p>电子邮件:{{.Email}}</p></body></html> 

大多数资源都解决了代码片段,并且进行了一些更进一步的修改,您将能够将参数传递到URL中,根据路线呈现数据等.我希望这可以使您了解如何轻松解决问题你的问题.祝你好运!

I'm not expecting to get the code written for me, I just want a nudge in the right direction.

I have a task to make a web server that listens to port 8080, on this server i shall present data that is readable to humans. The person accessing this server will get to these paths using /1, /2, /3 etc. The data that is to be presented is to be gathered from 5 different APIs, and all of these are to return data in JSON format.

Also all of the paths are to be rendered to the person using Go templates.

How would one go about doing this? I might sound like i'm giving out homework, but I really new to this and need some help.

解决方案

You will have lots of resources from the answers. I would like to give some simple code you can test if it's fitting your needs:

Have a simple folder structure like this:

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

Inside main.go we create a http server listening on port 8080. Here is the entire code commented:

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
}

And then in the index.html just use:

<!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>

Most of the resources address the code snippet and with some more tinkering, you will be able to pass params into the URL, render the data according to the route etc. I hope this gives you an idea on how it's easy to solve your problem. Good luck!

这篇关于使用go设置Web服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆