agones.dev/agones@v1.53.0/pkg/util/httpserver/server.go (about)

     1  // Copyright 2024 Google LLC All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Package httpserver implements an http server that conforms to the
    16  // controller runner interface.
    17  package httpserver
    18  
    19  import (
    20  	"context"
    21  	"net/http"
    22  
    23  	"agones.dev/agones/pkg/util/runtime"
    24  	"github.com/pkg/errors"
    25  	"github.com/sirupsen/logrus"
    26  )
    27  
    28  // Server is a HTTPs server that conforms to the runner interface
    29  // we use in /cmd/controller.
    30  //
    31  //nolint:govet // ignore field alignment complaint, this is a singleton
    32  type Server struct {
    33  	http.ServeMux
    34  	Port string
    35  
    36  	Logger *logrus.Entry
    37  }
    38  
    39  // Run runs an http server on port :8080.
    40  func (s *Server) Run(ctx context.Context, _ int) error {
    41  	s.Logger.Info("Starting http server...")
    42  	if s.Port == "" {
    43  		s.Port = "8080"
    44  	}
    45  	srv := &http.Server{
    46  		Addr:    ":" + s.Port,
    47  		Handler: s,
    48  	}
    49  	go func() {
    50  		<-ctx.Done()
    51  		_ = srv.Shutdown(context.Background())
    52  	}()
    53  
    54  	if err := srv.ListenAndServe(); err != nil {
    55  		if err == http.ErrServerClosed {
    56  			s.Logger.WithError(err).Info("http server closed")
    57  		} else {
    58  			wrappedErr := errors.Wrap(err, "Could not listen on :"+s.Port)
    59  			runtime.HandleError(s.Logger.WithError(wrappedErr), wrappedErr)
    60  		}
    61  	}
    62  	return nil
    63  }