創(chuàng)建一個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
}
//定義一個結(jié)構(gòu)
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"`
}