go - 使用golang server同时服务flutterweb app和rest api
问题描述
我有一个颤动的移动应用程序,它通过 rest api 使用来自 golang 服务器的服务。它在各个方面都运行良好。我将应用程序移植到一个 Web 项目并创建了一个 golang 服务器来提供它的文件。也可以正常工作。这是从 SO 的另一个问题复制而来的 golang http 服务器代码。
package main
import (
"flag"
"log"
"net/http"
)
func main() {
port := flag.String("p", "8181", "port to serve on")
directory := flag.String("d", "web", "the directory of static file to host")
flag.Parse()
http.Handle("/", http.FileServer(http.Dir(*directory)))
log.Printf("Serving %s on HTTP port: %s\n", *directory, *port)
log.Fatal(http.ListenAndServe(":"+*port, nil))
}
这是其余 api 服务器的(部分)代码:
func main() {
r := mux.NewRouter()
http.Handle("/", r)
content, err := ioutil.ReadFile("bdlocation.txt")
if err != nil {
log.Fatal(err)
}
BdLocation = string(content)
r.HandleFunc("/api/getmenu", get_menu).Methods("GET")
r.HandleFunc("/api/getmenuitems", get_menu_items).Methods("GET")
r.HandleFunc("/api/image/{file}", WebHandler).Methods("GET")
... etc...
log.Fatal(http.ListenAndServe(":8000", r))
}
我的问题的当前状态是:
- Web 服务器在界面、导航等方面都可以正常工作,就像移动应用程序一样。
- 从移动应用程序使用时,其余服务器正常工作。
- 不能让两人交流。我的目标是在浏览器中调用 Flutter Web 应用程序,然后从那里使用其余的 api。
这是我到目前为止所尝试的:
- 在同一台机器上运行两台服务器,每台服务器都有自己的端口。我从浏览器调用了 localhost:8181 (网络应用程序),并从这个环境中调用了 http:8000/api/xxxx 以获取其余数据。不工作
- 试图将两台服务器“合并”成这样的东西:
func main() {
r := mux.NewRouter()
http.Handle("/", r)
content, err := ioutil.ReadFile("bdlocation.txt")
if err != nil {
log.Fatal(err)
}
BdLocation = string(content)
directory := flag.String("d", "web", "the directory of static file to host")
flag.Parse()
// if the call is http:localhost, serve the web app...
r.Handle("/", http.FileServer(http.Dir(*directory)))
// if it is somethins else serve the corresponding api function
r.HandleFunc("/api/getmenu", get_menu).Methods("GET")
... etc...
r.HandleFunc("/api/image/{file}", WebHandler).Methods("GET")
log.Fatal(http.ListenAndServe(":8000", r))
}
也没有工作,虽然它编译正确。
我还不得不说,当我尝试这些方法时,我没有收到任何错误消息,而且我不是调试 Web 应用程序的专家,所以我无法提供更多关于可能出错的线索。
谢谢你的帮助。
解决方案
推荐阅读
- java - 如何在一系列单选按钮之上添加一个简单的字符串?
- ios - 从 UITableView 和 Firebase 中删除单元格
- sql - Update multiple rows in SQL Server with different table
- sas - 使用 Proc sql 获取许多变量的统计信息
- dart - 颤振中的侧面径向菜单
- azure-web-app-service - 如何在 azurewebsites.net 下为 Azure App Service 应用程序添加第二个域名?
- ios - 如何从另一个类访问一个类中的值?斯威夫特 4
- dart - 为什么更新列表
ListView 中使用的那个无法更新显示? - reactjs - 如何在 React JS 中的组件之间传递值?
- java - 多个 Spring 控制器是否应该指向同一个视图文件?