1

im just learning Go, and creating simple web app. But every time i start my localhost in GO(even i stopped process in terminal), it doesnt close port. So how can i close it.

here's code

const portNumber = ":8080"
func main() {
http.HandleFunc("/", Home)
http.HandleFunc("/about", About)

fmt.Println(fmt.Sprintf("Starting on port %s", portNumber))
_ = http.ListenAndServe(portNumber, nil)
}

I did research on net, but couldnt find solution, so hope you can help me. Thanks

2
  • What do you mean with "closing a port"? Do you want to block it? Free it up? Close a connection? Hide it behind a firewall? Commented Jan 14, 2023 at 13:14
  • Does this answer your question? How to stop http.ListenAndServe() Commented Jan 15, 2023 at 20:03

2 Answers 2

1

The term you are looking for is graceful shutdown. Google it up and you will find code similar to the one below with explanation.

func startHttpServer() {
srv := &http.Server{
    Addr:    ListenAddr,
}

idleConnsClosed := make(chan struct{})

go func() {
    // for graceful shutdown..
    sigint := make(chan os.Signal, 1)
    signal.Notify(sigint, os.Interrupt)
    <-sigint

    // We received an interrupt signal, shut down.
    log.Println("Shutting down server...")
    if err := srv.Shutdown(context.Background()); err != nil {
        // Error from closing listener(s), or context timeout:
        log.Printf("HTTP server Shutdown: %v", err)
    }
    close(idleConnsClosed)
}()

// blocking service of connections
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
    log.Fatalf("HTTP server ListenAndServe: %v", err)
}

<-idleConnsClosed 
}
Sign up to request clarification or add additional context in comments.

Comments

0

I think first it is important to rephrase your question and really understand what you're asking. There's no such thing as a closed HTTP port. So this is how exactly HTTP Server works on a very high level:

  1. So when you ask the HTTP server to start listening at a port, You're basically asking OS, to create an Internet socket that represents an endpoint. From the endpoint, I mean IP: PORT.

  2. That socket in particular is a TCP internet socket in the case of HTTP 1,1.1 and 2.

  3. That socket is running in listen phase and is listening for any incoming connection requests. And if it receives any incoming request then the kernel will simply do a 3 way TCP handshake and after a successful handshake kernel creates a connection object and hand it over to the process that represents your backend application, where you're listening for any new connection created. So you see PORT was always there in your system, You didn't create a new PORT while starting the HTTP server, but basically created an Internet socket object and asked your kernel to start listening on that PORT for a new connection and hand it over to your backend application when connection created. So you're basically asking how I stop listening at that endpoint and ask Kernel to delete that internet socket. Below is a rough code segment to give you an idea of how to do it.

     import (
     "context"
     "log"
     "net/http"
     "os"
     "os/signal"
     "syscall"
     "time"
     )
     func main() {
         server := &http.Server{Addr: ":8080", Handler: myHandler}
         go server.ListenAndServe()
    
         interrupt := make(chan os.Signal, 1)
         signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)
    
         <-interrupt
         log.Println("Shutting down server...")
    
         ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
         defer cancel()
    
         if err := server.Shutdown(ctx); err != nil {
             log.Fatal("Server forced to shutdown:", err)
         }
         log.Println("Server stopped")
     }
    
     func myHandler(w http.ResponseWriter, r *http.Request) {
         // Handle requests
     }
    
    
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.