zoukankan      html  css  js  c++  java
  • Use Go Micro Web

    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.

  • 相关阅读:
    子程序的设计
    多重循环程序设计
    汇编语言的分支程序设计与循环程序设计
    代码调试之串口调试2
    毕昇杯模块之光照强度传感器
    毕昇杯之温湿度采集模块
    【CSS】盒子模型 之 IE 与W3C的盒子模型对比
    【css】盒子模型 之 概述
    【css】盒子模型 之 弹性盒模型
    【网络】dns_probe_finished_nxdomain 错误
  • 原文地址:https://www.cnblogs.com/Jedimaster/p/13729867.html
Copyright © 2011-2022 走看看