helper/prodHelper.go
package helper
type ProdsRequest struct {
Size int `form:"size"`
}
prod_main.go
package main
import (
"flag"
"fmt"
"gitee.com/Hind3ight/easy-go-micro/go-micro/helper"
"gitee.com/Hind3ight/easy-go-micro/go-micro/model"
"github.com/gin-gonic/gin"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/web"
"github.com/micro/go-plugins/registry/consul" // micro版本变迁
"log"
)
func main() {
consulReg := consul.NewRegistry(registry.Addrs("192.168.31.246:8500"))
r := gin.Default()
v1Group := r.Group("/v1")
{
v1Group.Handle("POST", "/prods", func(c *gin.Context) {
var pr helper.ProdsRequest
err := c.Bind(&pr)
if err != nil || pr.Size <= 0 {
pr = helper.ProdsRequest{Size: 2}
}
c.JSON(200, gin.H{
"data": model.GenFakerProdList(pr.Size),
})
})
}
server := web.NewService(
web.Name("prodService"),
web.Address(flagParser()),
//web.Address(":8001"),
web.Handler(r),
web.Registry(consulReg),
web.Metadata(map[string]string{"protocol" : "http"}),// 为注册的服务添加Metadata,指定请求协议为http
)
err := server.Run()
if err != nil {
log.Fatal("Server Run error: ", err)
}
}
// simple 自定义命令行解析
func flagParser() string {
serverAddress := flag.String("server_address", ":8080", "服务端口")
flag.Parse()
fmt.Println("端口号:", *serverAddress)
return *serverAddress
}