如何在特定路径上提供Go服务?

huangapple go评论76阅读模式
英文:

How to serve Go on a particular path?

问题

如何将服务器的默认URL更改为http://localhost:8000/api,而不是http:localhost:8000

我一直在使用以下代码:

http.ListenAndServe(":8000")

我需要做哪些更改?

英文:

How do I make the server listen on http://localhost:8000/api as the default URL instead of http:localhost:8000?

I've been using this

http.ListenAndServe(":8000")

What changes should I bring?

答案1

得分: 2

你不能在一个URL上进行监听,你需要监听一个TCP端口。

所以在你的情况下是8080

监听端口的服务器需要根据特定的URI做出反应。

所以要使API在/api/...上可用,它们的路径应该以/api/开头。

    http.Handle("/api/someAPI", apiHandler)
    http.Handle("/api/someOtherAPI", otherHandler)
    . . .

另外,当使用Kubernetes Ingress或其他反向代理设置时,可以配置URI重写(示例)。这在处理已经硬编码为特定URI但需要在不同URI上公开的现有应用程序时非常有用。

英文:

You can't listen on a URL, you listen on a TCP port.

So 8080 in your case.

It's up to the server that listens on the port to react on specific URIs.

So to make APIs available on /api/..., their path should begin with /api/.

    http.Handle("/api/someAPI", apiHandler)
    http.Handle("/api/someOtherAPI", otherHandler)
    . . .

Alternatively when using Kubernetes ingress or some other reverse proxy setup, it's possible to configure URI rewriting (example). This is useful when dealing with an existing application that is hardcoded to a specific URI but needs to be exposed on a different URI.

huangapple
  • 本文由 发表于 2021年9月20日 13:24:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/69249421.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定