[Solved] ReverseProxy will not shutdown

I am trying to build a simple reverse proxy, but I am running in to problems when I want to stop it. The shutdown command is executed but the proxy is still running. Does anyone know what to do?

package main

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

func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	go func() {
		time.Sleep(1 * time.Second)
		err := Stop()
		if err != nil {
			log.Println(err)
		}
	}()

	err := Start("localhost:9999", "http://dockerhost:8065")
	if err != nil {
		log.Print(err)
	}
}

var reverseProxy http.Server

func Start(bind string, remote string) error {
	remoteUrl, err := url.Parse(remote)
	if err != nil {
		return err
	}

	reverseProxy := http.Server{
		Handler: proxyHandler(remoteUrl),
		Addr:    bind,
	}

	err = reverseProxy.ListenAndServe()
	if err != nil {
		return err
	}

	log.Print("Stopped proxy")

	return nil
}

func Stop() error {
	log.Print("Stopper proxy.")
	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
	defer cancel()

	log.Print("Stopper proxy..")
	if err := reverseProxy.Shutdown(ctx); err != nil {
		return err
	}
	log.Print("Stopper proxy...")
	return nil
}

func proxyHandler(remote *url.URL) *httputil.ReverseProxy {
	handler := func(req *http.Request) {
		req.URL.Host = remote.Host
		req.URL.Scheme = remote.Scheme
		req.ParseForm()
		log.Printf("%+v", req)
	}
	return &httputil.ReverseProxy{
		Director: handler,
	}
}

Hi @muhaha,

The issue here is that you need to change this:

reverseProxy := http.Server{
	Handler: proxyHandler(remoteUrl),
	Addr:    bind,
}

To this:

reverseProxy = http.Server{
	Handler: proxyHandler(remoteUrl),
	Addr:    bind,
}

Otherwise you are creating a new reverse proxy object that isn’t being assigned to your global variable and therefore Stop won’t actually do anything. :slight_smile:

Thanks you so much, now I can finally go to sleep :sweat_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.