1 // Package rest provides RESTful serialization of AWS requests and responses.
18 "github.com/aws/aws-sdk-go/aws"
19 "github.com/aws/aws-sdk-go/aws/awserr"
20 "github.com/aws/aws-sdk-go/aws/request"
23 // RFC822 returns an RFC822 formatted timestamp for AWS protocols
24 const RFC822 = "Mon, 2 Jan 2006 15:04:05 GMT"
26 // Whether the byte value can be sent without escaping in AWS URLs
27 var noEscape [256]bool
29 var errValueNotSet = fmt.Errorf("value not set")
32 for i := 0; i < len(noEscape); i++ {
33 // AWS expects every character except these to be escaped
34 noEscape[i] = (i >= 'A' && i <= 'Z') ||
35 (i >= 'a' && i <= 'z') ||
36 (i >= '0' && i <= '9') ||
44 // BuildHandler is a named request handler for building rest protocol requests
45 var BuildHandler = request.NamedHandler{Name: "awssdk.rest.Build", Fn: Build}
47 // Build builds the REST component of a service request.
48 func Build(r *request.Request) {
50 v := reflect.ValueOf(r.Params).Elem()
51 buildLocationElements(r, v, false)
56 // BuildAsGET builds the REST component of a service request with the ability to hoist
57 // data from the body.
58 func BuildAsGET(r *request.Request) {
60 v := reflect.ValueOf(r.Params).Elem()
61 buildLocationElements(r, v, true)
66 func buildLocationElements(r *request.Request, v reflect.Value, buildGETQuery bool) {
67 query := r.HTTPRequest.URL.Query()
69 // Setup the raw path to match the base path pattern. This is needed
70 // so that when the path is mutated a custom escaped version can be
71 // stored in RawPath that will be used by the Go client.
72 r.HTTPRequest.URL.RawPath = r.HTTPRequest.URL.Path
74 for i := 0; i < v.NumField(); i++ {
76 if n := v.Type().Field(i).Name; n[0:1] == strings.ToLower(n[0:1]) {
81 field := v.Type().Field(i)
82 name := field.Tag.Get("locationName")
86 if kind := m.Kind(); kind == reflect.Ptr {
88 } else if kind == reflect.Interface {
89 if !m.Elem().IsValid() {
96 if field.Tag.Get("ignore") != "" {
101 switch field.Tag.Get("location") {
102 case "headers": // header maps
103 err = buildHeaderMap(&r.HTTPRequest.Header, m, field.Tag)
105 err = buildHeader(&r.HTTPRequest.Header, m, name, field.Tag)
107 err = buildURI(r.HTTPRequest.URL, m, name, field.Tag)
109 err = buildQueryString(query, m, name, field.Tag)
112 err = buildQueryString(query, m, name, field.Tag)
122 r.HTTPRequest.URL.RawQuery = query.Encode()
123 if !aws.BoolValue(r.Config.DisableRestProtocolURICleaning) {
124 cleanPath(r.HTTPRequest.URL)
128 func buildBody(r *request.Request, v reflect.Value) {
129 if field, ok := v.Type().FieldByName("_"); ok {
130 if payloadName := field.Tag.Get("payload"); payloadName != "" {
131 pfield, _ := v.Type().FieldByName(payloadName)
132 if ptag := pfield.Tag.Get("type"); ptag != "" && ptag != "structure" {
133 payload := reflect.Indirect(v.FieldByName(payloadName))
134 if payload.IsValid() && payload.Interface() != nil {
135 switch reader := payload.Interface().(type) {
137 r.SetReaderBody(reader)
139 r.SetBufferBody(reader)
141 r.SetStringBody(reader)
143 r.Error = awserr.New("SerializationError",
144 "failed to encode REST request",
145 fmt.Errorf("unknown payload type %s", payload.Type()))
153 func buildHeader(header *http.Header, v reflect.Value, name string, tag reflect.StructTag) error {
154 str, err := convertType(v, tag)
155 if err == errValueNotSet {
157 } else if err != nil {
158 return awserr.New("SerializationError", "failed to encode REST request", err)
161 header.Add(name, str)
166 func buildHeaderMap(header *http.Header, v reflect.Value, tag reflect.StructTag) error {
167 prefix := tag.Get("locationName")
168 for _, key := range v.MapKeys() {
169 str, err := convertType(v.MapIndex(key), tag)
170 if err == errValueNotSet {
172 } else if err != nil {
173 return awserr.New("SerializationError", "failed to encode REST request", err)
177 header.Add(prefix+key.String(), str)
182 func buildURI(u *url.URL, v reflect.Value, name string, tag reflect.StructTag) error {
183 value, err := convertType(v, tag)
184 if err == errValueNotSet {
186 } else if err != nil {
187 return awserr.New("SerializationError", "failed to encode REST request", err)
190 u.Path = strings.Replace(u.Path, "{"+name+"}", value, -1)
191 u.Path = strings.Replace(u.Path, "{"+name+"+}", value, -1)
193 u.RawPath = strings.Replace(u.RawPath, "{"+name+"}", EscapePath(value, true), -1)
194 u.RawPath = strings.Replace(u.RawPath, "{"+name+"+}", EscapePath(value, false), -1)
199 func buildQueryString(query url.Values, v reflect.Value, name string, tag reflect.StructTag) error {
200 switch value := v.Interface().(type) {
202 for _, item := range value {
203 query.Add(name, *item)
205 case map[string]*string:
206 for key, item := range value {
207 query.Add(key, *item)
209 case map[string][]*string:
210 for key, items := range value {
211 for _, item := range items {
212 query.Add(key, *item)
216 str, err := convertType(v, tag)
217 if err == errValueNotSet {
219 } else if err != nil {
220 return awserr.New("SerializationError", "failed to encode REST request", err)
228 func cleanPath(u *url.URL) {
229 hasSlash := strings.HasSuffix(u.Path, "/")
231 // clean up path, removing duplicate `/`
232 u.Path = path.Clean(u.Path)
233 u.RawPath = path.Clean(u.RawPath)
235 if hasSlash && !strings.HasSuffix(u.Path, "/") {
241 // EscapePath escapes part of a URL path in Amazon style
242 func EscapePath(path string, encodeSep bool) string {
244 for i := 0; i < len(path); i++ {
246 if noEscape[c] || (c == '/' && !encodeSep) {
249 fmt.Fprintf(&buf, "%%%02X", c)
255 func convertType(v reflect.Value, tag reflect.StructTag) (string, error) {
256 v = reflect.Indirect(v)
258 return "", errValueNotSet
262 switch value := v.Interface().(type) {
266 str = base64.StdEncoding.EncodeToString(value)
268 str = strconv.FormatBool(value)
270 str = strconv.FormatInt(value, 10)
272 str = strconv.FormatFloat(value, 'f', -1, 64)
274 str = value.UTC().Format(RFC822)
276 b, err := json.Marshal(value)
280 if tag.Get("location") == "header" {
281 str = base64.StdEncoding.EncodeToString(b)
286 err := fmt.Errorf("Unsupported value for param %v (%s)", v.Interface(), v.Type())