使用Golang实现linux管道处理

在项目中遇到了一个和其他项目整合的一个需求,我们的虚拟机是以UUID的方式创建的,名称是存储在主节点的数据库中,整合的平台是使用ssh的方式到我们的服务器上进行数据采集,但是采集的虚拟机名称是UUID,并不是虚拟机的名称,这时候就需要进行转换UUID到VmName。

鉴于对方平台的命令较多,且后期可能会有改的可能,但是需求只有将UUID替换成Name的需求,所以经过考虑我们采用以原有命令结果作为管道输入,程序进行替换,然后再输出的方式进行。

linux的管道内容是通过os.Stdin中读取的,我们可以通过像普通文件一样操作os.Stdin,下面是管道读取的程序示例:

package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
)

func main() {
    fileInfo, _ := os.Stdin.Stat()
    if (fileInfo.Mode() & os.ModeNamedPipe) != os.ModeNamedPipe {
        log.Fatal("The command is intended to work with pipes.")
    }
    s := bufio.NewScanner(os.Stdin)
    for s.Scan() {
        fmt.Println(s.Text())
    }
}

上面这个程序是用来获取管道输入然后再输出出来的过程,现在加入替换UUID的示例:

package main

import (
   "bufio"
   "fmt"
   "log"
   "os"
   "strings"
)

func main() {
   fileInfo, _ := os.Stdin.Stat()
   // 判定是否为管道输入
   if (fileInfo.Mode() & os.ModeNamedPipe) != os.ModeNamedPipe {
      log.Fatal("The command is intended to work with pipes.")
   }
   s := bufio.NewScanner(os.Stdin)
   // outputString 用来存储管道输入的原始字符串,并后期进行替换
   outputString := ""
   for s.Scan() {
      outputString += s.Text()+"\n"
   }
   // getUuidNameMap 函数用来获取UUID和Name的对应关系
   uuidMap,err := getUuidNameMap()
   if err != nil{
      // 这里的设计哲学是:如果管道处理函数报错了,那将原有输入直接输出
      fmt.Println(outputString)
   }
   for uuid,name := range uuidMap{
      // UUID 替换为 Name, 全文无限替换
      outputString = strings.Replace(outputString,uuid,name,-1)
   }
   // 最后输出变更后的字符串
   fmt.Println(outputString)
}

func getUuidNameMap()(uuidMap map[string]string,err error){
   // 增加获取对应关系的处理逻辑
   return
}

其中getUuidNameMap逻辑需要根据各自需求进行处理。

这里只是举了个例子使用Golang进行管道处理,管道能处理的事情还很多,从另一个方面也说明Golang语言作为运维语言是十分快捷高效的。

About the author

liuyuhang

View all posts

38 Comments

  • This video is presenting does vital flow work
    but also try to cover the following subject:https://www.facebook.com/pages/category/Health—Wellness-Website/Vital-flow-reviews-102135748499657/

    -vital flow for prostate

    -vitalflow prostate really works

    -vitalflow prostate support reviews

    One thing I noticed when I was researching info on does
    vital flow work was the absence of appropriate details.

    Does vital flow work nevertheless is an subject that I know something about.

    This video therefore should be relevant and of interest
    to you.

    ~~~~~~~~~~~~~~~~~~~~~

    Follow our video clips about does vital flow work as
    well as other comparable topics on

    I’m really impressed with your writing skills and also with the
    layout on your blog. Is this a paid theme or did you modify it yourself?
    Either way keep up the nice quality writing, it’s rare to see a
    nice blog like this one today.

  • Hiya, I am really glad I have found this info. Today bloggers publish just about gossip and internet stuff and this is actually annoying. A good web site with interesting content, this is what I need. Thanks for making this web-site, and I will be visiting again. Do you do newsletters by email? Jocelin Briano Pelage

  • I was very pleased to discover this great site. I need to to thank you for your time just for this fantastic read!! I definitely savored every little bit of it and I have you saved as a favorite to see new information on your site. sasilu.se/map31.php mamma teresa meny Stace Nelson Orlena

  • Thanks for the sensible critique. Me & my neighbor were just preparing to do a little research about this. We got a grab a book from our area library but I think I learned more from this post. I am very glad to see such excellent information being shared freely out there. Austine Warden Eberly

  • obviously like your website however you have to test the spelling on several of your posts. A number of them are rife with spelling problems and I find it very troublesome to tell the reality however I will definitely come back again. Brinn Eldridge Horton

  • Thanks Kevin, great article! Is that dripper glass or plastic? It looks cool whatever material it is. Carilyn Griffin Anastasie

  • I have to convey my affection for your kindness supporting those who require assistance with this particular concern. Your real commitment to passing the solution around turned out to be extraordinarily good and have continually encouraged people like me to realize their pursuits. This warm and helpful recommendations entails this much to me and somewhat more to my colleagues. With thanks; from everyone of us. Sheree Taddeo Marrilee

  • When I initially commented I seem to have clicked on the -Notify me when new comments are added- checkbox and from now on every time a comment is added I recieve four emails with the exact same comment. Perhaps there is a way you can remove me from that service? Thanks a lot! Dasya Alvy Reiche

  • magnificent issues altogether, you simply received a new reader. What might you suggest about your post that you just made a few days in the past? Any sure? Karee Colet Helge

  • fantastic submit, very informative. I’m wondering why the opposite specialists of this sector don’t realize this.
    You must proceed your writing. I am sure, you’ve a huge
    readers’ base already!

  • I’m really enjoying the design and layout of your site. It’s a very easy on the eyes
    which makes it much more pleasant for me to come here and visit more
    often. Did you hire out a developer to create your theme?
    Fantastic work!

  • I know this web page presents quality depending articles and other material, is there any other web site which presents these kinds of information in quality? Mada Dorie Sebastien

  • Have you ever thought about adding a little bit more
    than just your articles? I mean, what you say is fundamental and everything.
    However imagine if you added some great graphics or videos to give your
    posts more, “pop”! Your content is excellent but with pics
    and clips, this site could undeniably be one of the greatest
    in its niche. Terrific blog!

  • Wow that was odd. I just wrote an very long comment but after I
    clicked submit my comment didn’t appear. Grrrr…

    well I’m not writing all that over again. Anyways, just wanted to say superb blog!

  • You made some good points there. I looked on the internet for the subject and found most people will approve with your website. Alameda Lefty Woodsum

  • Hurrah! After all I got a webpage from where I know how to actually take helpful facts regarding my study and knowledge. Cinnamon Townsend Budde

  • I am genuinely delighted to glance at this blog posts which includes plenty of valuable data, thanks for providing such statistics. Avie Harmon Ranger

发表评论

电子邮件地址不会被公开。 必填项已用*标注