|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +package server |
| 19 | + |
| 20 | +import ( |
| 21 | + "context" |
| 22 | + "net/http" |
| 23 | + "time" |
| 24 | + |
| 25 | + "github.com/apache/apisix-ingress-controller/internal/provider" |
| 26 | +) |
| 27 | + |
| 28 | +type Server struct { |
| 29 | + server *http.Server |
| 30 | + mux *http.ServeMux |
| 31 | +} |
| 32 | + |
| 33 | +func (s *Server) Start(ctx context.Context) error { |
| 34 | + stop := make(chan error, 1) |
| 35 | + go func() { |
| 36 | + if err := s.server.ListenAndServe(); err != nil && err != http.ErrServerClosed { |
| 37 | + stop <- err |
| 38 | + } |
| 39 | + close(stop) |
| 40 | + }() |
| 41 | + select { |
| 42 | + case <-ctx.Done(): |
| 43 | + shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 44 | + defer cancel() |
| 45 | + return s.server.Shutdown(shutdownCtx) |
| 46 | + case err := <-stop: |
| 47 | + return err |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +func (s *Server) Register(pathPrefix string, registrant provider.RegisterHandler) { |
| 52 | + subMux := http.NewServeMux() |
| 53 | + registrant.Register(pathPrefix, subMux) |
| 54 | + s.mux.Handle(pathPrefix+"/", http.StripPrefix(pathPrefix, subMux)) |
| 55 | + s.mux.HandleFunc(pathPrefix, func(w http.ResponseWriter, r *http.Request) { |
| 56 | + http.Redirect(w, r, pathPrefix+"/", http.StatusPermanentRedirect) |
| 57 | + }) |
| 58 | +} |
| 59 | + |
| 60 | +func NewServer(addr string) *Server { |
| 61 | + mux := http.NewServeMux() |
| 62 | + return &Server{ |
| 63 | + server: &http.Server{ |
| 64 | + Addr: addr, |
| 65 | + Handler: mux, |
| 66 | + }, |
| 67 | + mux: mux, |
| 68 | + } |
| 69 | +} |
0 commit comments