donglingsai2880 2013-07-16 00:21
浏览 118

如何优雅地或有效地将地图写入http.ResponseWriter

I was wondering what would be the most elegant way to write a Key Value Form encoded map to a http.ResponseWriter.

Respond(kv map[string]string) {
  for key, value := range kv {
    fmt.Fprintf(a.w, "%s:%s
", key, value)
  }  
}

I have to follow this Key-Value format:

Key-Value Form Encoding

A message in Key-Value form is a sequence of lines. Each line begins with a key, followed by a colon, and the value associated with the key. The line is terminated by a single newline (UCS codepoint 10, " "). A key or value MUST NOT contain a newline and a key also MUST NOT contain a colon.

Additional characters, including whitespace, MUST NOT be added before or after the colon or newline. The message MUST be encoded in UTF-8 to produce a byte string.

I thought about using encoding/csv but isn't that a bit overkill?

Edit: What I came up with so far. (Thanks for all the suggested answers)

http://godoc.org/github.com/kugutsumen/encoding/keyvalue

https://github.com/kugutsumen/encoding/tree/master/keyvalue

  • 写回答

3条回答 默认 最新

  • dongzhi9032 2013-07-16 01:26
    关注

    If you want to write strings to any Writer in Go (including an http.ResponseWriter) without using the fmt package, you can use the bytes package to read the strings and write them to the Writer.

    The code below creates a Buffer from the key and value strings using bytes.NewBufferString and then writes them to the http.ResponseWriter using the WriteTo function.

    package main
    
    import (
        "bytes"
        "log"
        "net/http"
    )
    
    func main() {
        kv := map[string]string{"key1": "val1", "key2": "val2", "key3": "val3", "key4": "val4", "key5": "val5"}
        http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
            for key, value := range kv {
                kvw := bytes.NewBufferString(key + ":" + value + "
    ")
                if _, err := kvw.WriteTo(w); err != nil {
                    log.Fatal("Error: ", err)
                }
            }
        })
        if err := http.ListenAndServe("localhost:8080", nil); err != nil {
            log.Fatal("ListenAndServe: ", err)
        }
    }
    

    Will output:

    key1:val1
    key2:val2
    key3:val3
    key4:val4
    key5:val5

    Hopefully that's close to what you're after.

    EDIT: You can also use the strings.Reader Type and the corresponding WriteTo function from the strings package.

    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算