Go kit(1)微服务入门 - Go语言中文社区

Go kit(1)微服务入门


1.基础入门

在这里插入图片描述
你好! 这是你第一次使用 **Markdown编辑器** 所展示的欢迎页。如果你想学习如何使用Markdown
在这里插入图片描述

第一步创建UserService

package Services
type IUserService interface {
    GetName(userid int) string
}
type UserService struct{}
func (this UserService) GetName(userid int) string {
    if userid == 101 {
        return "jerry"
    }
    return "guest"
}

第二步:创建EndPoint

在这里插入图片描述

package Services

import (
    "context"
    "github.com/go-kit/kit/endpoint"
)

type UserRequest struct { //封装User请求结构体
    Uid int `json:"uid"`
}

type UserResponse struct {
    Result string `json:"result"`
}

func GenUserEnPoint(userService IUserService) endpoint.Endpoint {
    return func(ctx context.Context, request interface{}) (response interface{}, err error) {
        r := request.(UserRequest)           //通过类型断言获取请求结构体
        result := userService.GetName(r.Uid) //
        return UserResponse{Result: result}, nil
    }
}

第二步:创建Transport

在这里插入图片描述

package Services

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

func DecodeUserRequest(c context.Context, r *http.Request) (interface{}, error) { //这个函数决定了使用哪个request结构体来请求
    if r.URL.Query().Get("uid") != "" {
        uid, _ := strconv.Atoi(r.URL.Query().Get("uid"))
        return UserRequest{Uid: uid}, nil
    }
    return nil,errors.New("参数错误")/
}

func EncodeUserResponse(ctx context.Context,w http.ResponseWriter,response interface{}) error{
    w.Header().Set("Content-type","application/json") //设置响应格式为json,这样客户端接收到的值就是json,就是把我们设置的UserResponse给json化了

    return json.NewEncoder(w).Encode(response)//判断响应格式是否正确
}

如何改变文本的样式

一般是三层架构三个文件夹,我这里演示方便把三层的东西都放到了一个文件夹中

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_44575411/article/details/106426804
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢