微服務實戰Go Micro v3 系列(三)-啟動HTTP服務


這篇就是使用 go-micro 的 http 創建一個可以調用接口的微服務HTTP

源碼地址

系列文章

httpServer

這里我們使用 gin 框架結合 go-micro 來進行編寫

首先 創建一個 http 目錄,並在該目錄下創建 main.go,寫入下面代碼

package main

import (
	httpServer "github.com/asim/go-micro/plugins/server/http/v3"
	"github.com/asim/go-micro/v3"
	"github.com/asim/go-micro/v3/logger"
	"github.com/asim/go-micro/v3/registry"
	"github.com/asim/go-micro/v3/server"
	"github.com/gin-gonic/gin"
	"go-micro-examples/http/handler"
)

const (
	ServerName = "go.micro.web.DemoHTTP" // server name
)

func main() {
	// Create service
	srv := httpServer.NewServer(
		server.Name(ServerName),
		server.Address(":8080"),
	)
    
	gin.SetMode(gin.ReleaseMode)
	router := gin.New()
	router.Use(gin.Recovery())

	// register router
	demo := handler.NewDemo()
	demo.InitRouter(router)

	hd := srv.NewHandler(router)
	if err := srv.Handle(hd); err != nil {
		logger.Fatal(err)
	}

	// Create service
	service := micro.NewService(
		micro.Server(srv),
		micro.Registry(registry.NewRegistry()),
	)
	service.Init()

	// Run service
	if err := service.Run(); err != nil {
		logger.Fatal(err)
	}
}

使用 gin 進行初始化路由

在 http 目錄創建 handler\handler.go

package handler

import (
	"context"
	"github.com/asim/go-micro/v3"
	"github.com/gin-gonic/gin"
	helloworld "go-micro-examples/helloworld/proto"
)

//demo
type demo struct{}

func NewDemo() *demo {
	return &demo{}
}

func (a *demo) InitRouter(router *gin.Engine) {
	router.POST("/demo", a.demo)
}

func (a *demo) demo(c *gin.Context) {
	// create a service
	service := micro.NewService()
	service.Init()

	client := helloworld.NewHelloworldService("go.micro.srv.HelloWorld", service.Client())

	rsp, err := client.Call(context.Background(), &helloworld.Request{
		Name: "world!",
	})
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": err.Error()})
		return
	}

	c.JSON(200, gin.H{"code": 200, "msg": rsp.Msg})
}

postman測試

在啟動兩個微服務之后,如下圖:

使用 postman 進行測試,調用成功並返回 "hello world!"


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM