【问题标题】:How Should I Get Data From My Own Webpage Using Go? [duplicate]我应该如何使用 Go 从我自己的网页中获取数据? [复制]
【发布时间】:2022-01-20 00:33:01
【问题描述】:

我希望能够使用 Go 程序从我的网站格式化数据。现在我的网站是用 PHP 编写的,我正在从 SQL 表中获取数据。我的网站代码是

<?php
include("connection.php");
$sql = mysqli_query($con, "SELECT * FROM talk");
while ($info = $sql->fetch_assoc()) {
    echo "Name: " . $info['name'];
    echo "<br>";
    echo "Message: " . $info['message'];
    echo "<br>";
}

页面当前显示

Name: John
Message: My name is John
Name: Doe
Message: My name is Doe

我希望能够使用 Go 脚本来获取名称和消息的信息。我愿意为我的网站更改代码,我写的非常简单,以便能够简要了解我正在尝试做的事情。

【问题讨论】:

  • 在 Go 中你应该分两步完成:第一:从数据库中读取,第二:在模板上显示数据
  • @Ahmed 是否有可能我只能从网页上阅读,或者我必须与 Go 中的数据库进行交互?我的目标是让我的网页使用 PHP 通过与数据库交互来显示数据,然后让 Go 从网页中获取 NameMessage 信息。
  • 我知道一种方法。这是编写 Go 代码的方式。您从数据库中读取数据。然后在html模板上显示数据我没试过直接把Go代码写到html模板里,也许还有另一种我不知道的方式。我见过一些允许将 Go 代码直接写入 html 的 3rd 方库。但我没有尝试过,我认为这不是正确的方法。
  • 这里有一些可能有用的标题:gowebexamples.com
  • 使 php 输出 JSON 而不是 html(然后它很容易被调用脚本解析)并使你的 go 程序发送一个 http 请求来检索数据

标签: php sql go


【解决方案1】:

我建议这两个步骤:

第 1 步:PHP 代码生成纯文本(例如:“John;Message 1\n;Doe;Message2\n”)(参见此处:[PHP - 呈现纯文本][1][https://stackoverflow. com/questions/4506679/rendering-plain-text-through-php)][1]

第 2 步:在 GO 中,使用 http GET 从 PHP 服务器请求信息:

打包phpgo

进口( “fmt” “io/ioutil” “网络/http” “字符串” )

func getFromPhp(url string, filename string) ([]string, error) { var err 错误

fmt.Printf("Downloading %s...\n", filename)

//Execute the HTTP GET request
resp, err := http.Get(url)
if err != nil || resp.StatusCode != 200 {
    err = fmt.Errorf("failed download from %s ", url)
    return err
}

//Read the content the from response body
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil || resp.StatusCode != 200 {
    err = fmt.Errorf("failed download from %s ", url)
    return err
}

//Put each element of data in a slice
infos := strings.Split(string(body), "\n")

return infos, err

}

[1]:Rendering plain text through PHP)

【讨论】:

    猜你喜欢
    • 2011-05-30
    • 2019-09-17
    • 2021-02-06
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    相关资源
    最近更新 更多