Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

http.Serverはcontextがdoneしたときにいい感じにエラーを返してくれない #243

Merged
merged 3 commits into from
Nov 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file removed backend/state-manager/cmd/main
Binary file not shown.
50 changes: 41 additions & 9 deletions backend/state-manager/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"context"
"fmt"
"log/slog"
"net"
"net/http"
Expand Down Expand Up @@ -29,6 +30,19 @@ const (
Prod
)

func (a AppEnv) String() string {
switch a {
case Dev:
return "dev"
case Test:
return "test"
case Prod:
return "prod"
default:
return "unknown"
}
}

var appEnv AppEnv = Dev
var (
version = "develop"
Expand Down Expand Up @@ -65,19 +79,19 @@ func init() {
func main() {
err := godotenv.Load(".env")
if err != nil {
slog.Default().Error("Error loading .env file")
slog.Default().Error("Error loading .env file", slog.Any("error", err))
os.Exit(1)
}
baseCtx, cancel := context.WithCancel(context.Background())
defer cancel()
ctx, stop := signal.NotifyContext(baseCtx, os.Interrupt)
signalCtx, stop := signal.NotifyContext(baseCtx, os.Interrupt)
defer stop()

go func() {
<-ctx.Done()
<-signalCtx.Done()
slog.Default().Info("signal received")
}()

eg, ctx := errgroup.WithContext(ctx)
eg, ctx := errgroup.WithContext(signalCtx)

r := chi.NewRouter()
// r.Use(middleware.Recoverer)
Expand Down Expand Up @@ -108,18 +122,36 @@ func main() {
ReadHeaderTimeout: 60 * time.Second,
BaseContext: func(net.Listener) context.Context { return ctx },
}
eg.Go(srv.ListenAndServe)
eg.Go(func() error {
errC := make(chan error)
go func() {
slog.Default().Info("start http server")
if err := srv.ListenAndServe(); err != nil {
slog.Default().Error("http server error", slog.Any("error", err))
errC <- err
}
}()
select {
case err := <-errC:
return fmt.Errorf("http server error: %w", err)
case <-ctx.Done():
slog.Default().Info("Interrupted at http server")
return ctx.Err()
}
})
//go operation.Handler()
eg.Go(func() error {
slog.Default().Info("start mqtt handler")
return mqtt_handler.StartHandler(ctx)
err := mqtt_handler.StartHandler(ctx)
return fmt.Errorf("mqtt handler error: %w", err)
})

// errGroup.Waitはeg.Goが全てerrorを返すまでwaitする
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

今回の場合はeg.Go(srv.ListenAndServe)がエラーを返さなかったので起こった事象ですね~

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

なるほど

if err := eg.Wait(); err != nil {
slog.Default().Error("error in sub goroutine at main", err)
slog.Default().Error("error in sub goroutine at main", slog.Any("error", err))
}
slog.Default().Info("shutting down server")
newCtx, srvTimeOutCancel := context.WithTimeout(context.Background(), 3*time.Second)
defer srvTimeOutCancel()
srv.Shutdown(newCtx)
<-newCtx.Done()
}
9 changes: 5 additions & 4 deletions backend/state-manager/pkg/mqtt_handler/mqtt_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"log/slog"
"os"
"strings"

Expand Down Expand Up @@ -66,9 +66,10 @@ func StartHandler(ctx context.Context) error {
log.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
topicHandler(cc, msg)
case <-ctx.Done():
fmt.Println("Interrupted")
slog.Default().Info("Interrupted at mqtt_handler")
cc.Disconnect(1000)
return nil
slog.Default().Info("Disconnected from mqtt broker")
return ctx.Err()
}
}
}
Expand Down Expand Up @@ -149,7 +150,7 @@ func getState(cc mqtt.Client, target string, id string) {
token.Wait()
return
}
raw, err := ioutil.ReadFile("../settings/esp/" + id + ".json")
raw, err := os.ReadFile("../settings/esp/" + id + ".json")
if err != nil {
log.Println(err.Error())
return
Expand Down