英文:
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)
}
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论