Service
go-kit 提供了原生的 kitgen 工具,可以方便的生成 service服务
安装 kitgen
- Fetch the
inlinefiles
utility. Go generate will use it to create your
code:go get github.com/nyarly/inlinefiles
- Install the binary for easy access to
kitgen
. Run the following commands:
cd $GOPATH/src/github.com/go-kit/kit/cmd/kitgen
go install
# Check installation by running:
kitgen -h
使用方法
- 定义你的服务 . 创建定义了service interface 的 .go 文件
// service.go
package profilesvc // don't forget to name your package
type Service interface {
PostProfile(ctx context.Context, p Profile) error
// ...
}
type Profile struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
// ...
}
- Generate 生成代码
kitgen ./service.go
# kitgen has a couple of flags that you may find useful
# keep all code in the root directory
kitgen -repo-layout flat ./service.go
# put generated code elsewhere
kitgen -target-dir ~/Projects/gohome/src/home.com/kitchenservice/brewcoffee
生成的代码结构如下:
- endpoint
- endpoint.go
- http
- http.go
- service
- service.go
代码如下:
endpoint.go
package endpoints
import (
"context"
"tmp/service"
"github.com/go-kit/kit/endpoint"
)
type PostProfileRequest struct {
P service.Profile
}
type PostProfileResponse struct {
Err error
}
func MakePostProfileEndpoint(s service.Service) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(PostProfileRequest)
err := s.PostProfile(ctx, req.P)
return PostProfileResponse{Err: err}, nil
}
}
type Endpoints struct {
PostProfile endpoint.Endpoint
}
http.go
package http
import (
"context"
"encoding/json"
"net/http"
"tmp/endpoints"
httptransport "github.com/go-kit/kit/transport/http"
)
func NewHTTPHandler(endpoints endpoints.Endpoints) http.Handler {
m := http.NewServeMux()
m.Handle("/postprofile", httptransport.NewServer(endpoints.PostProfile, DecodePostProfileRequest, EncodePostProfileResponse))
return m
}
func DecodePostProfileRequest(_ context.Context, r *http.Request) (interface{}, error) {
var req endpoints.PostProfileRequest
err := json.NewDecoder(r.Body).Decode(&req)
return req, err
}
func EncodePostProfileResponse(_ context.Context, w http.ResponseWriter, response interface{}) error {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
return json.NewEncoder(w).Encode(response)
}
service.go
package service
import (
"context"
"errors"
)
type Profile struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
}
type Service struct {
}
func (s Service) PostProfile(ctx context.Context, p Profile) error {
panic(errors.New("not implemented"))
}
最后编辑: Simon 文档更新时间: 2021-09-27 12:49 作者:Simon