• go语言增加参数访问


    1.服务提供者

    // 数据模型
    type ProdsRequest struct {
    Size int `form:"size"`
    }

    import
    ( "github.com/gin-gonic/gin" "github.com/micro/go-micro/registry" "github.com/micro/go-micro/web" "github.com/micro/go-plugins/registry/consul" ) // 使用gin框架 func main() { consulReg := consul.NewRegistry( registry.Addrs("127.0.0.1:8500"), ) ginRouter := gin.Default() v1Group := ginRouter.Group("/v1") { v1Group.Handle("POST", "/prods", func(context *gin.Context) { //声明变量 var gr ProdsRequest //获取绑定数据到gr变量中,底层用的指针这里要传变量地址 err := context.Bind(&gr) if err!=nil || gr.Size<=0 { gr=ProdsRequest{Size:2} } context.JSON(200, gin.H{ "data": NewProdList(gr.Size), "size":gr.Size, }) }) } web.NewService(web.Address(":8001"), web.Handler(ginRouter), web.Registry(consulReg), web.Name("product")).Run() }

    2.服务消费者

    import (
        "context"
        "fmt"
        "github.com/micro/go-micro/client"
        "github.com/micro/go-micro/client/selector"
        "github.com/micro/go-micro/registry"
        myhttp "github.com/micro/go-plugins/client/http"
        "github.com/micro/go-plugins/registry/consul"
        _ "io/ioutil"
        "log"
        _ "net/http"
    )
    type RequestParam struct {
        //消费者服务的数据模型可以不加`form:"size"`
        Size int /*`form:"size"`*/
    }
    
    func callApi2(s selector.Selector) {
        myclient := myhttp.NewClient(
            client.Selector(s),
            client.ContentType("application/json"),
        )
        //消费者传参用map
        //req := myclient.NewRequest("product", "/v1/prods", map[string]int{"size":5})
        req := myclient.NewRequest("product", "/v1/prods", RequestParam{Size: 1})
        var rsp map[string]interface{}
        err := myclient.Call(context.Background(), req, &rsp)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(rsp)
    }
    
    func main() {
        consulReg := consul.NewRegistry(
            registry.Addrs("127.0.0.1:8500"))
        mySelector := selector.NewSelector(
            selector.Registry(consulReg),
            selector.SetStrategy(selector.RoundRobin),
        )
        callApi2(mySelector)
    }
  • 相关阅读:
    leetcode练习:26. Remove Duplicates from Sorted Array
    leetcode练习:11. Container With Most Water
    leetcode练习:5. Longest Palindromic Substring
    leetcode练习:2.Add Two Numbers
    算法笔记:分治
    (排序回顾)快速排序
    (排序回顾)归并排序
    leetcode练习:2017/09/21~09/22
    算法笔记:递归&迭代
    在Treeview中节点的data属性中保存记录类型及其消除的办法
  • 原文地址:https://www.cnblogs.com/huqi96/p/14392384.html
Copyright © 2020-2023  润新知