mirror of
https://github.com/googleapis/genai-toolbox.git
synced 2026-04-09 03:02:26 -04:00
65 lines
1.7 KiB
Go
65 lines
1.7 KiB
Go
// Copyright 2024 Google LLC
|
|
//
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
|
|
package server
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/go-chi/chi/v5/middleware"
|
|
)
|
|
|
|
// Server contains info for running an instance of Toolbox. Should be instantiated with NewServer().
|
|
type Server struct {
|
|
conf Config
|
|
router chi.Router
|
|
}
|
|
|
|
// NewServer returns a Server object based on provided Config.
|
|
func NewServer(cfg Config) *Server {
|
|
r := chi.NewRouter()
|
|
r.Use(middleware.Logger)
|
|
r.Use(middleware.Recoverer)
|
|
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
|
|
_, _ = w.Write([]byte("🧰 Hello world! 🧰"))
|
|
})
|
|
|
|
s := &Server{
|
|
conf: cfg,
|
|
router: r,
|
|
}
|
|
return s
|
|
}
|
|
|
|
// ListenAndServe starts an HTTP server for the given Server instance.
|
|
func (s *Server) ListenAndServe(ctx context.Context) error {
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
defer cancel()
|
|
|
|
addr := net.JoinHostPort(s.conf.Address, strconv.Itoa(s.conf.Port))
|
|
lc := net.ListenConfig{KeepAlive: 30 * time.Second}
|
|
l, err := lc.Listen(ctx, "tcp", addr)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to open listener for %q: %w", addr, err)
|
|
}
|
|
|
|
return http.Serve(l, s.router)
|
|
}
|