1// Copyright 2015 go-swagger maintainers
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//    http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package errors
16
17import (
18	"encoding/json"
19	"fmt"
20	"net/http"
21)
22
23// Validation represents a failure of a precondition
24type Validation struct {
25	code    int32
26	Name    string
27	In      string
28	Value   interface{}
29	message string
30	Values  []interface{}
31}
32
33func (e *Validation) Error() string {
34	return e.message
35}
36
37// Code the error code
38func (e *Validation) Code() int32 {
39	return e.code
40}
41
42// MarshalJSON implements the JSON encoding interface
43func (e Validation) MarshalJSON() ([]byte, error) {
44	return json.Marshal(map[string]interface{}{
45		"code":    e.code,
46		"message": e.message,
47		"in":      e.In,
48		"name":    e.Name,
49		"value":   e.Value,
50		"values":  e.Values,
51	})
52}
53
54// ValidateName produces an error message name for an aliased property
55func (e *Validation) ValidateName(name string) *Validation {
56	if e.Name == "" && name != "" {
57		e.Name = name
58		e.message = name + e.message
59	}
60	return e
61}
62
63const (
64	contentTypeFail    = `unsupported media type %q, only %v are allowed`
65	responseFormatFail = `unsupported media type requested, only %v are available`
66)
67
68// InvalidContentType error for an invalid content type
69func InvalidContentType(value string, allowed []string) *Validation {
70	values := make([]interface{}, 0, len(allowed))
71	for _, v := range allowed {
72		values = append(values, v)
73	}
74	return &Validation{
75		code:    http.StatusUnsupportedMediaType,
76		Name:    "Content-Type",
77		In:      "header",
78		Value:   value,
79		Values:  values,
80		message: fmt.Sprintf(contentTypeFail, value, allowed),
81	}
82}
83
84// InvalidResponseFormat error for an unacceptable response format request
85func InvalidResponseFormat(value string, allowed []string) *Validation {
86	values := make([]interface{}, 0, len(allowed))
87	for _, v := range allowed {
88		values = append(values, v)
89	}
90	return &Validation{
91		code:    http.StatusNotAcceptable,
92		Name:    "Accept",
93		In:      "header",
94		Value:   value,
95		Values:  values,
96		message: fmt.Sprintf(responseFormatFail, allowed),
97	}
98}
99