1 // Package rest provides RESTful serialization of AWS requests and responses.
17 "github.com/aws/aws-sdk-go/aws"
18 "github.com/aws/aws-sdk-go/aws/awserr"
19 "github.com/aws/aws-sdk-go/aws/request"
20 "github.com/aws/aws-sdk-go/private/protocol"
23 // Whether the byte value can be sent without escaping in AWS URLs
24 var noEscape [256]bool
26 var errValueNotSet = fmt.Errorf("value not set")
29 for i := 0; i < len(noEscape); i++ {
30 // AWS expects every character except these to be escaped
31 noEscape[i] = (i >= 'A' && i <= 'Z') ||
32 (i >= 'a' && i <= 'z') ||
33 (i >= '0' && i <= '9') ||
41 // BuildHandler is a named request handler for building rest protocol requests
42 var BuildHandler = request.NamedHandler{Name: "awssdk.rest.Build", Fn: Build}
44 // Build builds the REST component of a service request.
45 func Build(r *request.Request) {
47 v := reflect.ValueOf(r.Params).Elem()
48 buildLocationElements(r, v, false)
53 // BuildAsGET builds the REST component of a service request with the ability to hoist
54 // data from the body.
55 func BuildAsGET(r *request.Request) {
57 v := reflect.ValueOf(r.Params).Elem()
58 buildLocationElements(r, v, true)
63 func buildLocationElements(r *request.Request, v reflect.Value, buildGETQuery bool) {
64 query := r.HTTPRequest.URL.Query()
66 // Setup the raw path to match the base path pattern. This is needed
67 // so that when the path is mutated a custom escaped version can be
68 // stored in RawPath that will be used by the Go client.
69 r.HTTPRequest.URL.RawPath = r.HTTPRequest.URL.Path
71 for i := 0; i < v.NumField(); i++ {
73 if n := v.Type().Field(i).Name; n[0:1] == strings.ToLower(n[0:1]) {
78 field := v.Type().Field(i)
79 name := field.Tag.Get("locationName")
83 if kind := m.Kind(); kind == reflect.Ptr {
85 } else if kind == reflect.Interface {
86 if !m.Elem().IsValid() {
93 if field.Tag.Get("ignore") != "" {
98 switch field.Tag.Get("location") {
99 case "headers": // header maps
100 err = buildHeaderMap(&r.HTTPRequest.Header, m, field.Tag)
102 err = buildHeader(&r.HTTPRequest.Header, m, name, field.Tag)
104 err = buildURI(r.HTTPRequest.URL, m, name, field.Tag)
106 err = buildQueryString(query, m, name, field.Tag)
109 err = buildQueryString(query, m, name, field.Tag)
119 r.HTTPRequest.URL.RawQuery = query.Encode()
120 if !aws.BoolValue(r.Config.DisableRestProtocolURICleaning) {
121 cleanPath(r.HTTPRequest.URL)
125 func buildBody(r *request.Request, v reflect.Value) {
126 if field, ok := v.Type().FieldByName("_"); ok {
127 if payloadName := field.Tag.Get("payload"); payloadName != "" {
128 pfield, _ := v.Type().FieldByName(payloadName)
129 if ptag := pfield.Tag.Get("type"); ptag != "" && ptag != "structure" {
130 payload := reflect.Indirect(v.FieldByName(payloadName))
131 if payload.IsValid() && payload.Interface() != nil {
132 switch reader := payload.Interface().(type) {
134 r.SetReaderBody(reader)
136 r.SetBufferBody(reader)
138 r.SetStringBody(reader)
140 r.Error = awserr.New("SerializationError",
141 "failed to encode REST request",
142 fmt.Errorf("unknown payload type %s", payload.Type()))
150 func buildHeader(header *http.Header, v reflect.Value, name string, tag reflect.StructTag) error {
151 str, err := convertType(v, tag)
152 if err == errValueNotSet {
154 } else if err != nil {
155 return awserr.New("SerializationError", "failed to encode REST request", err)
158 name = strings.TrimSpace(name)
159 str = strings.TrimSpace(str)
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)
176 keyStr := strings.TrimSpace(key.String())
177 str = strings.TrimSpace(str)
179 header.Add(prefix+keyStr, str)
184 func buildURI(u *url.URL, v reflect.Value, name string, tag reflect.StructTag) error {
185 value, err := convertType(v, tag)
186 if err == errValueNotSet {
188 } else if err != nil {
189 return awserr.New("SerializationError", "failed to encode REST request", err)
192 u.Path = strings.Replace(u.Path, "{"+name+"}", value, -1)
193 u.Path = strings.Replace(u.Path, "{"+name+"+}", value, -1)
195 u.RawPath = strings.Replace(u.RawPath, "{"+name+"}", EscapePath(value, true), -1)
196 u.RawPath = strings.Replace(u.RawPath, "{"+name+"+}", EscapePath(value, false), -1)
201 func buildQueryString(query url.Values, v reflect.Value, name string, tag reflect.StructTag) error {
202 switch value := v.Interface().(type) {
204 for _, item := range value {
205 query.Add(name, *item)
207 case map[string]*string:
208 for key, item := range value {
209 query.Add(key, *item)
211 case map[string][]*string:
212 for key, items := range value {
213 for _, item := range items {
214 query.Add(key, *item)
218 str, err := convertType(v, tag)
219 if err == errValueNotSet {
221 } else if err != nil {
222 return awserr.New("SerializationError", "failed to encode REST request", err)
230 func cleanPath(u *url.URL) {
231 hasSlash := strings.HasSuffix(u.Path, "/")
233 // clean up path, removing duplicate `/`
234 u.Path = path.Clean(u.Path)
235 u.RawPath = path.Clean(u.RawPath)
237 if hasSlash && !strings.HasSuffix(u.Path, "/") {
243 // EscapePath escapes part of a URL path in Amazon style
244 func EscapePath(path string, encodeSep bool) string {
246 for i := 0; i < len(path); i++ {
248 if noEscape[c] || (c == '/' && !encodeSep) {
251 fmt.Fprintf(&buf, "%%%02X", c)
257 func convertType(v reflect.Value, tag reflect.StructTag) (str string, err error) {
258 v = reflect.Indirect(v)
260 return "", errValueNotSet
263 switch value := v.Interface().(type) {
267 str = base64.StdEncoding.EncodeToString(value)
269 str = strconv.FormatBool(value)
271 str = strconv.FormatInt(value, 10)
273 str = strconv.FormatFloat(value, 'f', -1, 64)
275 format := tag.Get("timestampFormat")
276 if len(format) == 0 {
277 format = protocol.RFC822TimeFormatName
278 if tag.Get("location") == "querystring" {
279 format = protocol.ISO8601TimeFormatName
282 str = protocol.FormatTime(format, value)
285 return "", errValueNotSet
287 escaping := protocol.NoEscape
288 if tag.Get("location") == "header" {
289 escaping = protocol.Base64Escape
291 str, err = protocol.EncodeJSONValue(value, escaping)
293 return "", fmt.Errorf("unable to encode JSONValue, %v", err)
296 err := fmt.Errorf("unsupported value for param %v (%s)", v.Interface(), v.Type())