github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/transports/handler.go (about)

     1  /*
     2   * Copyright 2023 Wang Min Xiang
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   * 	http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   *
    16   */
    17  
    18  package transports
    19  
    20  import (
    21  	"github.com/aacfactory/configures"
    22  	"github.com/aacfactory/errors"
    23  	"github.com/aacfactory/fns/context"
    24  	"github.com/aacfactory/logs"
    25  )
    26  
    27  type Handler interface {
    28  	Handle(w ResponseWriter, r Request)
    29  }
    30  
    31  type HandlerFunc func(ResponseWriter, Request)
    32  
    33  func (f HandlerFunc) Handle(w ResponseWriter, r Request) {
    34  	f(w, r)
    35  }
    36  
    37  type MuxHandlerOptions struct {
    38  	Log    logs.Logger
    39  	Config configures.Config
    40  }
    41  
    42  type MuxHandler interface {
    43  	Name() string
    44  	Construct(options MuxHandlerOptions) error
    45  	Match(ctx context.Context, method []byte, path []byte, header Header) bool
    46  	Handler
    47  }
    48  
    49  func NewMux() *Mux {
    50  	return &Mux{
    51  		handlers: make([]MuxHandler, 0, 1),
    52  	}
    53  }
    54  
    55  type Mux struct {
    56  	handlers []MuxHandler
    57  }
    58  
    59  func (mux *Mux) Add(handler MuxHandler) {
    60  	mux.handlers = append(mux.handlers, handler)
    61  }
    62  
    63  func (mux *Mux) Handle(w ResponseWriter, r Request) {
    64  	for _, handler := range mux.handlers {
    65  		matched := handler.Match(r, r.Method(), r.Path(), r.Header())
    66  		if matched {
    67  			handler.Handle(w, r)
    68  			return
    69  		}
    70  	}
    71  	w.Failed(errors.NotFound("fns: not found").WithMeta("handler", "mux"))
    72  }