micro负载均衡和http入参自动检查

1. 负载均衡

import (
    "context"
    "fmt"
    "github.com/micro/go-micro/client"
    "github.com/micro/go-micro/client/selector"
    "github.com/micro/go-micro/registry"
    "github.com/micro/go-micro/registry/etcd"
    myhttp "github.com/micro/go-plugins/client/http"
    "github.com/micro/go-plugins/registry/consul"
    Models "go-micro-study/bak/models"
    "io/ioutil"
    "log"
    "net/http"
)

func callApi2(s selector.Selector)  {
    myClient := myhttp.NewClient(client.Selector(s),
        client.ContentType("application/json"),
        )
   //请求注册中心里面的服务
    request := myClient.NewRequest("prodservice", "/v1/prods", Models.ProdsReq{Size: 1})
    var resp Models.ProdListResp

    err := myClient.Call(context.Background(), request, &resp)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(resp.Data)

    return
}

func main()  {
etcdReg := etcd.NewRegistry(registry.Addrs("127.0.0.1:2379"))

    mySeletor := selector.NewSelector( //负载均衡插件
        selector.Registry(etcdReg ),
        selector.SetStrategy(selector.Random), //随机
        )

    callApi2(mySeletor)
}

2.http参数检查:

第三方validator库使用

package main

import (
    "gopkg.in/go-playground/validator.v9"
    "log"
    "micro-tools/AppLib"
    "testing"
)

type Users struct {
    Username string `validate:"required,min=6,max=20" vmsg:"用户名必须大于6位以上"`
    Userpwd string `validate:"required,min=6,max=18" vmsg:"用户密码必须大于6位以上"`
    //TestName string `validate:"required,username" vmsg:"用户名不正确"`
    Usertags []string `validate:"required,min=1,max=5,unique,dive,usertag" vmsg:"用户标签不合法"`
}

func TestStruct(t *testing.T) {
    userTags := []string{"aa", "bb","cc","dd","ee"}
    valid := validator.New()
    _ = AppLib.AddRegexTag("usertag", "^[\u4e00-\u9fa5a-zA-Z0-9]{2,4}$", valid)
    //_ = AppLib
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值