eintopf.info@v0.13.16/service/status/transport.go (about)

     1  // Copyright (C) 2022 The Eintopf authors
     2  //
     3  // This program is free software: you can redistribute it and/or modify
     4  // it under the terms of the GNU Affero General Public License as
     5  // published by the Free Software Foundation, either version 3 of the
     6  // License, or (at your option) any later version.
     7  //
     8  // This program is distributed in the hope that it will be useful,
     9  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    10  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    11  // GNU Affero General Public License for more details.
    12  //
    13  // You should have received a copy of the GNU Affero General Public License
    14  // along with this program.  If not, see <https://www.gnu.org/licenses/>.
    15  
    16  package status
    17  
    18  import (
    19  	"encoding/json"
    20  	"net/http"
    21  	"time"
    22  
    23  	"github.com/go-chi/chi/v5"
    24  
    25  	"eintopf.info/internal/xhttp"
    26  )
    27  
    28  // Router returns a new status router.
    29  func Router(service Service) func(chi.Router) {
    30  	server := &server{service}
    31  	return func(r chi.Router) {
    32  		r.Options("/", xhttp.CorsHandler)
    33  
    34  		// swagger:route GET /status/ status status
    35  		//
    36  		// Returns status information about the server.
    37  		//
    38  		//     Responses:
    39  		//       200: statusResponse
    40  		//       500: internalError
    41  		//       503: serviceUnavailable
    42  		r.Get("/", server.status)
    43  	}
    44  }
    45  
    46  type server struct {
    47  	service Service
    48  }
    49  
    50  // swagger:response statusResponse
    51  type statusResponse struct {
    52  	//in:body
    53  	Body Status
    54  }
    55  
    56  func (s *server) status(w http.ResponseWriter, r *http.Request) {
    57  	status := s.service.Status()
    58  	data, err := json.Marshal(status)
    59  	if err != nil {
    60  		xhttp.WriteInternalError(r.Context(), w, err)
    61  		return
    62  	}
    63  	w.Write(data)
    64  }
    65  
    66  // Middleware returns a new status middleware.
    67  // It collects information about requests.
    68  func Middleware(service Service) func(next http.Handler) http.Handler {
    69  	return func(next http.Handler) http.Handler {
    70  		fn := func(w http.ResponseWriter, r *http.Request) {
    71  			start := time.Now()
    72  			next.ServeHTTP(w, r)
    73  			service.RequestServed(time.Now().Sub(start))
    74  		}
    75  		return http.HandlerFunc(fn)
    76  	}
    77  }