Use Go Micro Web with HTTP Handler

The go-micro is a very powerful framework to establish a complete microservice backend network.

go-micro has several types of services, one service called go.micro.web is just a wrapper for standard HTTP server from Golang. Another advantage to use go.micro.web rather than go.micro.api is that, user could directly use any 3rd party HTTP framework in the microservice, and do not have to use built-in api.Request/api.Response structures to process the HTTP request.

During our benchmark, the serialization operations for api.Request/api.Response is quite slow, and not convenient enought to retrieve all headers of HTTP request.

Here is an example about how to use gorilla/mux to work with go.micro.web to serve a REST+WebSocket server.

package main

import (
    "net/http"
    "time"

    "github.com/gorilla/mux"
    "github.com/gorilla/websocket"
    log "github.com/micro/go-micro/v2/logger"
    "github.com/micro/go-micro/v2/web"
)

func EventHandler(w http.ResponseWriter, r *http.Request) {
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Errorf("failed to upgrade request [%v] to websocket", r)
    }
    defer conn.Close()

    for {
        t, msg, err := conn.ReadMessage()
        if err != nil {
            log.Error(err)
            break
        }

        log.Info(t, msg)

        e := Event{StatusCode: time.Now().Unix()}
        err = conn.WriteJSON(e)
        if err != nil {
            log.Error(err)
            break
        }
    }
}

func main() {
    svc := web.NewService(web.Name("go.micro.web.helloworld"))

    if err := svc.Init(); err != nil {
        log.Fatal(err)
    }

    router := mux.NewRouter()
    router.HandleFunc("/event", EventHandler)
    svc.Handle("/", router)

    if err := svc.Run(); err != nil {
        log.Fatal(err)
    }
}

That's it, so easy right ? You do not have to use anything related to api.Request/api.Response, but everything is the same as standard usage.

How to call this API ? By default, it should be accessible from http://localhost:8083/helloworld/event, it depends on at which port your go.micro.web is running.

This way of working has a lot of advantage, it allows to embed all REST handlers into go-micro eco-system easy, much better than api.Request/api.Response, we heavily use this way in our web applications.

posted @ 2020-09-25 14:11  Bo Schwarzstein  阅读(105)  评论(0编辑  收藏