web

  1. package main
  2. import (
  3. "net/http"
  4. "github.com/micro/go-micro/v2/util/log"
  5. "github.com/micro/go-micro/v2/web"
  6. )
  7. func main() {
  8. server := web.NewService(web.Address(":8080"))
  9. server.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
  10. w.Write([]byte("pong\n"))
  11. })
  12. log.Fatal(server.Run())
  13. }

go mod

  1. require (
  2. github.com/micro/go-micro/v2 v2.9.1
  3. )

启动服务器

  1. go run main.go

测试

  1. $curl localhost:8080/ping
  2. pong

gin

  1. package main
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/micro/go-micro/v2/util/log"
  5. "github.com/micro/go-micro/v2/web"
  6. )
  7. func main() {
  8. r := gin.Default()
  9. r.GET("/ping", func(c *gin.Context) {
  10. c.Writer.Write([]byte("pong\n"))
  11. })
  12. server := web.NewService(web.Address(":8080"))
  13. server.Handle("/ping", r)
  14. log.Fatal(server.Run())
  15. }

go.mod文件

  1. require (
  2. github.com/gin-gonic/gin v1.6.3
  3. github.com/micro/go-micro/v2 v2.9.1
  4. )