Go-kit构建微服务(二)发布服务

创建一个server,完成一个加法运算。

import (

"context"

"encoding/json"

"log"

"net/http"

"github.com/go-kit/kit/endpoint"

httptransport "github.com/go-kit/kit/transport/http"

"gokitbook/group.better.com/server/grouprequest"

"gokitbook/group.better.com/server/groupresponse"

)

//定义一个接口

type GroupServicer interface {

Add(int, int) int

}

//定义一个结构

type groupService struct{}

//add 方法

func (groupService) Add(a int, b int) int {

return a + b

}

func main() {

svc := groupService{}

addHandler := httptransport.NewServer(

makeAddEndpoint(svc),

grouprequest.DecodeAddRequest,

encodeResponse,

)

http.Handle("/add", addHandler)

log.Fatal(http.ListenAndServe(":8080", nil))

}

func makeAddEndpoint(svc groupService) endpoint.Endpoint {

return func(ctx context.Context, request interface{}) (interface{}, error) {

req := request.(grouprequest.AddRequest)

v := svc.Add(req.A, req.B)

return groupresponse.AddResponse{v}, nil

}

}

func encodeResponse(_ context.Context, w http.ResponseWriter, response interface{}) error {

return json.NewEncoder(w).Encode(response)

}


request:

package grouprequest

import (
    "context"
    "encoding/json"
    "net/http"
)

type AddRequest struct {
    A int `json:"a"`
    B int `json:"b"`
}

func DecodeAddRequest(_ context.Context, r *http.Request) (interface{}, error) {
    var request AddRequest
    if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
        return nil, err
    }
    return request, nil
}

response

package groupresponse

type AddResponse struct {
    V int `json:"v"`
}

Go-kit构建微服务(二)发布服务_第1张图片
1.png

你可能感兴趣的:(Go-kit构建微服务(二)发布服务)