how to create a reverse proxy in golang

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

how to create a reverse proxy in golang

问题

我想使用golang中的net包从stl库创建一个反向代理。我使用httputil来创建反向代理。但是当我向代理服务器发出请求时,它返回404错误。

以下是代理服务器的代码:

package main

import (
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
)

func main() {
	demoUrl, err := url.Parse("http://localhost:1000/run/")
	if err != nil {
		log.Fatal(err)
		return
	}
	proxy := httputil.NewSingleHostReverseProxy(demoUrl)
	http.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
		proxy.ServeHTTP(rw, r)
	})
	http.ListenAndServe(":2000", nil)
}

以下是原始服务器的代码:

package main

import (
	"net/http"
)

func main() {
	http.HandleFunc("/run", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("I am running"))
	})
	http.ListenAndServe(":1000", nil)
}

请告诉我我在这里漏掉了什么,以及如何修复这个错误!请

英文:

I wants to make a reverse proxy in golang using net package from stl library. Used httputil for creating reverse proxy. But when I make request to the proxy server it return 404 error.

Here is the proxy server code

package main

import (
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
)

func main() {
	demoUrl , err := url.Parse("http://localhost:1000/run/")
	if err!=nil{
		log.Fatal(err)
		return
	}
	proxy := httputil.NewSingleHostReverseProxy(demoUrl)
	http.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
		proxy.ServeHTTP(rw, r)
	})
	http.ListenAndServe(":2000", nil)
}

Here is the origin server code :

package main

import (
	"net/http"
)

func main(){
	http.HandleFunc("/run", func(w http.ResponseWriter, r *http.Request){
		w.Write([]byte("I am running"))
	})
	http.ListenAndServe(":1000", nil)
}

Please tell what I am missing here and how to fix the bug! Please

答案1

得分: 1

路由器不匹配。
这将按预期工作。

...
func main(){
    http.HandleFunc("/run/", func(w http.ResponseWriter, r *http.Request){
        w.Write([]byte("我正在运行"))
    })
    http.ListenAndServe(":1000", nil)
}
...
英文:

The router doesn't match.
this will be working as expected.

...
func main(){
    http.HandleFunc("/run/", func(w http.ResponseWriter, r *http.Request){
        w.Write([]byte("I am running"))
    })
    http.ListenAndServe(":1000", nil)
}
...

huangapple
  • 本文由 发表于 2021年11月15日 22:42:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/69976212.html
匿名

发表评论

匿名网友

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

确定