This article is about using Go-Micro’s HTTP to create a microservice HTTP that can call an interface

The source address

  • The source address
  • Comprehensive micro service project of Airentals

httpServer

Here we write using the GIN framework in combination with Go-Micro

First create an HTTP directory and create main.go in that directory. Write the following code

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(a) {
	// 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)
	iferr := srv.Handle(hd); err ! =nil {
		logger.Fatal(err)
	}

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

	// Run service
	iferr := service.Run(); err ! =nil {
		logger.Fatal(err)
	}
}
Copy the code

Gin is used to initialize routes

Create handler\handler.go in the HTTP directory

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(a) *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!",})iferr ! =nil {
		c.JSON(200, gin.H{"code": 500."msg": err.Error()})
		return
	}

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

Postman test

After starting the two microservices, the following image appears:

Test with Postman, call successful and return “Hello world!”