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.

  • 相关阅读:
    jquery跨域3
    juery的跨域请求2
    jquery的跨域请求
    synchronized与Lock的区别
    springboot之启动原理解析及源码阅读
    java中Number类理解
    springboot中配置文件application.properties的理解
    restTemplate设置访问超时
    BigDecimal.setScale 处理java小数点
    NIO之FileChannel类的理解和使用
  • 原文地址:https://www.cnblogs.com/Jedimaster/p/13729867.html
Copyright © 2011-2022 走看看