一、入门 go micro,快速的搭建一个服务

380 阅读1分钟
基于net/http标准库监听路由
// @author Walker
// @time 2020/11/13 15:22
package main

import (
	"github.com/micro/go-micro/web"
	"net/http"
)

func main() {
	s := web.NewService(
		web.Address(":8001"),
	)

	s.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("simple server ..."))
	})

	s.Run()
}
运行服务后 CURL 访问
$ curl 127.0.0.1:8001

simple server ...
提高生产里,可以使用 WEB 框架来实现上面的路由,这里使用 Gin
// @author Walker
// @time 2020/11/13 15:28
package main

import (
	"github.com/gin-gonic/gin"
	"github.com/micro/go-micro/web"
	"net/http"
)

func main() {
	r := gin.Default()
	r.GET("/", func(c *gin.Context) {
		c.String(http.StatusOK, "gin server...")
	})

	s := web.NewService(
		web.Address(":8001"),
		web.Metadata(map[string]string{"protocol": "http"}),
		web.Handler(r),
	)

	s.Run()
}
同样运行服务,CURL 访问
$ curl 127.0.0.1:8001

gin server ...