~wallyworld/gwacl/fix-request-eof

« back to all changes in this revision

Viewing changes to utils.go

  • Committer: Tarmac
  • Author(s): Gavin Panella
  • Date: 2013-04-12 15:11:18 UTC
  • mfrom: (89.1.12 url-construction-alt)
  • Revision ID: tarmac-20130412151118-ufwtsh6y1mkwfui5
[r=jtv][bug=][author=allenap] Interpolate user data into URLs with correct escaping, or prevent bad data from getting interpolated.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
// Copyright 2013 Canonical Ltd.  This software is licensed under the
 
2
// GNU Lesser General Public License version 3 (see the file COPYING).
 
3
 
 
4
package gwacl
 
5
 
 
6
import (
 
7
    "fmt"
 
8
    "net/url"
 
9
    "strings"
 
10
)
 
11
 
 
12
// checkPathComponents checks that none of the passed components contains any
 
13
// special characters, where special means "needs percent-encoding in a URI",
 
14
// does not contain any forward slashes, and is not the string "..".
 
15
func checkPathComponents(components ...string) {
 
16
    for _, component := range components {
 
17
        if component != url.QueryEscape(component) {
 
18
            panic(fmt.Errorf("'%s' contains URI special characters", component))
 
19
        }
 
20
        if component == ".." {
 
21
            panic(fmt.Errorf("'..' is not allowed"))
 
22
        }
 
23
    }
 
24
}
 
25
 
 
26
// interpolateURL replaces occurrences of ___ (three underscores) with the
 
27
// components specified. Additionally, the components are percent-encoded
 
28
// (using net.url.QueryEscape) before being interpolated.
 
29
func interpolateURL(urlstring string, components ...string) string {
 
30
    components_count := len(components)
 
31
    replacement_count := strings.Count(urlstring, "___")
 
32
    if components_count != replacement_count {
 
33
        panic(fmt.Errorf("%d slot(s) but given %d replacement(s)",
 
34
            replacement_count, components_count))
 
35
    }
 
36
    for _, component := range components {
 
37
        component = url.QueryEscape(component)
 
38
        urlstring = strings.Replace(urlstring, "___", component, 1)
 
39
    }
 
40
    return urlstring
 
41
}