首页 > 解决方案 > 使用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))
}

我的问题的当前状态是:

  1. Web 服务器在界面、导航等方面都可以正常工作,就像移动应用程序一样。
  2. 从移动应用程序使用时,其余服务器正常工作。
  3. 不能让两人交流。我的目标是在浏览器中调用 Flutter Web 应用程序,然后从那里使用其余的 api。

这是我到目前为止所尝试的:

  1. 在同一台机器上运行两台服务器,每台服务器都有自己的端口。我从浏览器调用了 localhost:8181 (网络应用程序),并从这个环境中调用了 http:8000/api/xxxx 以获取其余数据。不工作
  2. 试图将两台服务器“合并”成这样的东西:
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 应用程序的专家,所以我无法提供更多关于可能出错的线索。

谢谢你的帮助。

标签: goflutter-web

解决方案


推荐阅读