duan2428 2014-10-05 18:44
浏览 127

一个HTTP分隔符来全部统治

I have a configuration file in the format of blah = foo. I would like to have entries like:

http = https://stackoverflow.com/questions,header keys and values,string to search for.

I'm okay requiring that the the url be urlecncoded. Is there any ASCII character I can use that won't be valid value anywhere in the above example (After splitting once on =)? My example uses a comma but I think that is valid in a header value?

After pouring through some RFCs I figure someone is more familiar with this can save me some pain.

Also my project is in Go if there are existing std library that might help with this...

  • 写回答

2条回答 默认 最新

  • douyamitong57935 2014-10-05 19:12
    关注

    You can use a non-ascii character and urlencode, for example using the middle dot (compose + ^ + . on linux):

    const sep = `·`
    const t = `http = https://stackoverflow.com/questions·string to search for·header=value·header=value`
    
    func parseLine(line string) (name, url, search string, headers []string) {
        idx := strings.Index(line, " = ")
        if idx == -1 {
            return
        }
        name = line[:idx]
        parts := strings.Split(line[idx+3:], sep)
        if len(parts) < 3 {
            // handle invalid line
        }
        url, search = parts[0], parts[1]
        headers = parts[2:]
        return
    }
    

    Although, using JSON is probably the best and most long-term maintainable option.

    For completeness sake, a json version would look like:

    type Site struct {
        Url     string
        Query   string
        Headers map[string]string
    }
    
    const t = `[
        {
            "url": "https://stackoverflow.com/questions",
            "query": "string to search for",
            "headers": {"header": "value", "header2": "value"}
        },
        {
            "url": "https://google.com",
            "query": "string to search for",
            "headers": {"header": "value", "header2": "value"}
        }
    ]`
    
    func main() {
        var sites []Site
        err := json.Unmarshal([]byte(t), &sites)
        fmt.Printf("%+v (%v)
    ", sites, err)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?