S
S
Sergey Romanov2020-04-15 12:45:48
go
Sergey Romanov, 2020-04-15 12:45:48

How to display a message at the end of a program?

We admit eats such simple code.

func main() {
  fmt.Println("start")

  defer func() {
        	fmt.Println("stop")
  }()

  Run()

  fmt.Scanln()
}


It starts up in a container. If an error occurs in Run, then both start and stop messages will be displayed, and if I set up the container, then there will be no stop message.

How can I make sure that the container's setup correctly completes the program? Well, or the message was logged anyway.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2020-04-15
@Serhioromano

To do this, you need to catch signals
https://gobyexample.com/signals
When the container stops, a SIGINT is sent to the program. It is necessary to catch it and correctly close the program.
defer is not used for this, but to ensure that some code is executed on return from a function or panic.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question