请给出go-kit的 分装的列子
时间: 2024-02-17 13:01:26 浏览: 135
以下是一个基于go-kit的简单例子:
```
package main
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/go-kit/kit/transport/http"
)
func main() {
var logger log.Logger
{
logger = log.NewLogfmtLogger(os.Stderr)
logger = log.With(logger, "timestamp", log.DefaultTimestampUTC)
logger = log.With(logger, "caller", log.DefaultCaller)
}
var (
listenAddr = ":8080"
)
var svc Service
{
svc = myService{}
svc = loggingMiddleware(logger)(svc)
}
var uppercaseHandler http.Handler
{
uppercaseHandler = http.NewServer(
makeUppercaseEndpoint(svc),
decodeUppercaseRequest,
encodeResponse,
)
}
http.Handle("/uppercase", uppercaseHandler)
errs := make(chan error, 2)
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
errs <- fmt.Errorf("%s", <-c)
}()
go func() {
level.Info(logger).Log("msg", "HTTP", "addr", listenAddr)
errs <- http.ListenAndServe(listenAddr, nil)
}()
level.Error(logger).Log("exit", <-errs)
}
// Service provides a simple string manipulation service.
type Service interface {
Uppercase(context.Context, string) (string, error)
}
type myService struct{}
func (myService) Uppercase(_ context.Context, s string) (string, error) {
if s == "" {
return "", ErrEmpty
}
return strings.ToUpper(s), nil
}
func makeUppercaseEndpoint(svc Service) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(uppercaseRequest)
v, err := svc.Uppercase(ctx, req.S)
if err != nil {
return uppercaseResponse{v, err.Error()}, nil
}
return uppercaseResponse{v, ""}, nil
}
}
type uppercaseRequest struct {
S string `json:"s"`
}
type uppercaseResponse struct {
V string `json:"v"`
Err string `json:"err,omitempty"`
}
func decodeUppercaseRequest(_ context.Context, r *http.Request) (interface{}, error) {
var request uppercaseRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
return nil, err
}
return request, nil
}
func encodeResponse(_ context.Context, w http.ResponseWriter, response interface{}) error {
return json.NewEncoder(w).Encode(response)
}
func loggingMiddleware(logger log.Logger) Middleware {
return func(next Service) Service {
return logmw{logger, next}
}
}
type Middleware func(Service) Service
type logmw struct {
logger log.Logger
next Service
}
func (mw logmw) Uppercase(ctx context.Context, s string) (output string, err error) {
defer func(begin time.Time) {
level.Info(mw.logger).Log(
"method", "uppercase",
"input", s,
"output", output,
"err", err,
"took", time.Since(begin),
)
}(time.Now())
output, err = mw.next.Uppercase(ctx, s)
return
}
var ErrEmpty = errors.New("empty string")
```
这个例子中定义了一个Service,提供了一个Uppercase方法,将输入字符串转换为大写。使用go-kit的httptransport将该方法封装成HTTP API。另外,还增加了一个loggingMiddleware,用于日志记录。
其中,Service、Endpoint和Middleware是go-kit的核心概念,用于实现微服务的组件化。Middleware用于对Service进行装饰,Endpoint用于将Service的方法封装成一个HTTP API,具有了统一的传输层约定。
阅读全文