Blame view

http.go 4.48 KB
ea858b8a7   Marko Tikvić   refactoring
1
  package webutility
64041a2ea   Marko Tikvić   first commit
2
3
  
  import (
64041a2ea   Marko Tikvić   first commit
4
  	"encoding/json"
ad8e9dd2a   Marko Tikvić   added middleware ...
5
  	"fmt"
d2ddf82ef   Marko Tikvić   started on new rbac
6
  	"net/http"
64041a2ea   Marko Tikvić   first commit
7
  )
9933169c8   Marko Tikvić   localization support
8
9
10
11
  type webError struct {
  	Request string `json:"request"`
  	Error   string `json:"error"`
  }
ad8e9dd2a   Marko Tikvić   added middleware ...
12
13
  // NotFoundHandlerFunc writes HTTP error 404 to w.
  func NotFoundHandlerFunc(w http.ResponseWriter, req *http.Request) {
9933169c8   Marko Tikvić   localization support
14
15
16
17
  	SetDefaultHeaders(w)
  	if req.Method == "OPTIONS" {
  		return
  	}
ad8e9dd2a   Marko Tikvić   added middleware ...
18
  	NotFound(w, req, fmt.Sprintf("Resource you requested was not found: %s", req.URL.String()))
9933169c8   Marko Tikvić   localization support
19
20
21
22
23
24
  }
  
  // SetDefaultHeaders set's default headers for an HTTP response.
  func SetDefaultHeaders(w http.ResponseWriter) {
  	w.Header().Set("Access-Control-Allow-Origin", "*")
  	w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS")
ad8e9dd2a   Marko Tikvić   added middleware ...
25
  	w.Header().Set("Access-Control-Allow-Headers", `Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization`)
9933169c8   Marko Tikvić   localization support
26
27
  	w.Header().Set("Content-Type", "application/json; charset=utf-8")
  }
a205e8f40   Marko Tikvić   changes
28
29
30
31
32
33
34
  func ReqLocale(req *http.Request, dflt string) string {
  	loc := req.FormValue("locale")
  	if loc == "" {
  		return dflt
  	}
  	return loc
  }
9933169c8   Marko Tikvić   localization support
35
  // 2xx
1b7dfab73   Marko Tikvić   Payload changed t...
36
  func Success(w http.ResponseWriter, payload interface{}, code int) {
9933169c8   Marko Tikvić   localization support
37
38
  	w.WriteHeader(code)
  	if payload != nil {
1b7dfab73   Marko Tikvić   Payload changed t...
39
  		json.NewEncoder(w).Encode(payload)
9933169c8   Marko Tikvić   localization support
40
41
42
43
  	}
  }
  
  // 200
1b7dfab73   Marko Tikvić   Payload changed t...
44
  func OK(w http.ResponseWriter, payload interface{}) {
9933169c8   Marko Tikvić   localization support
45
46
47
48
  	Success(w, payload, http.StatusOK)
  }
  
  // 201
1b7dfab73   Marko Tikvić   Payload changed t...
49
  func Created(w http.ResponseWriter, payload interface{}) {
9933169c8   Marko Tikvić   localization support
50
51
52
53
54
55
56
57
58
59
60
61
62
63
  	Success(w, payload, http.StatusCreated)
  }
  
  // 4xx; 5xx
  func Error(w http.ResponseWriter, r *http.Request, code int, err string) {
  	werr := webError{Error: err, Request: r.Method + " " + r.RequestURI}
  	w.WriteHeader(code)
  	json.NewEncoder(w).Encode(werr)
  }
  
  // 400
  func BadRequest(w http.ResponseWriter, r *http.Request, err string) {
  	Error(w, r, http.StatusBadRequest, err)
  }
9933169c8   Marko Tikvić   localization support
64
65
66
67
68
69
70
71
72
  // 401
  func Unauthorized(w http.ResponseWriter, r *http.Request, err string) {
  	Error(w, r, http.StatusUnauthorized, err)
  }
  
  // 403
  func Forbidden(w http.ResponseWriter, r *http.Request, err string) {
  	Error(w, r, http.StatusForbidden, err)
  }
1b7dfab73   Marko Tikvić   Payload changed t...
73
74
75
76
77
78
  // 404
  func NotFound(w http.ResponseWriter, r *http.Request, err string) {
  	Error(w, r, http.StatusNotFound, err)
  }
  
  // 409
9933169c8   Marko Tikvić   localization support
79
80
81
82
83
84
85
86
87
88
89
90
  func Conflict(w http.ResponseWriter, r *http.Request, err string) {
  	Error(w, r, http.StatusConflict, err)
  }
  
  // 500
  func InternalServerError(w http.ResponseWriter, r *http.Request, err string) {
  	Error(w, r, http.StatusInternalServerError, err)
  }
  
  ///
  /// Old API
  ///
d66628295   Marko Tikvić   cleaned up
91
92
93
  const (
  	templateHttpErr500_EN = "An internal server error has occurred."
  	templateHttpErr500_RS = "Došlo je do greške na serveru."
2ea67927f   Marko Tikvić   added support for...
94
  	templateHttpErr400_EN = "Bad request."
d66628295   Marko Tikvić   cleaned up
95
  	templateHttpErr400_RS = "Neispravan zahtev."
6620591d8   Marko Tikvić   moved DeliverPayl...
96
  	templateHttpErr404_EN = "Resource not found."
9933169c8   Marko Tikvić   localization support
97
  	templateHttpErr404_RS = "Resurs nije pronadjen."
d66628295   Marko Tikvić   cleaned up
98
99
100
  	templateHttpErr401_EN = "Unauthorized request."
  	templateHttpErr401_RS = "Neautorizovan zahtev."
  )
64041a2ea   Marko Tikvić   first commit
101

33fd58161   markotikvic   minor changes, sh...
102
  type httpError struct {
64041a2ea   Marko Tikvić   first commit
103
104
105
106
107
108
109
110
  	Error   []HttpErrorDesc `json:"error"`
  	Request string          `json:"request"`
  }
  
  type HttpErrorDesc struct {
  	Lang string `json:"lang"`
  	Desc string `json:"description"`
  }
6620591d8   Marko Tikvić   moved DeliverPayl...
111
112
113
114
115
116
117
  // DeliverPayload encodes payload as JSON to w.
  func DeliverPayload(w http.ResponseWriter, payload Payload) {
  	// Don't write status OK in the headers here. Leave it up for the caller.
  	// E.g. Status 201.
  	json.NewEncoder(w).Encode(payload)
  	payload.Data = nil
  }
e1fbb41f9   Marko Tikvić   added comments
118
  // ErrorResponse writes HTTP error to w.
33fd58161   markotikvic   minor changes, sh...
119
  func ErrorResponse(w http.ResponseWriter, r *http.Request, code int, desc []HttpErrorDesc) {
2d79a4120   Marko Tikvić   Responses contain...
120
  	err := httpError{desc, r.Method + " " + r.RequestURI}
64041a2ea   Marko Tikvić   first commit
121
122
123
  	w.WriteHeader(code)
  	json.NewEncoder(w).Encode(err)
  }
6620591d8   Marko Tikvić   moved DeliverPayl...
124
125
126
127
128
129
130
  // NotFoundResponse writes HTTP error 404 to w.
  func NotFoundResponse(w http.ResponseWriter, req *http.Request) {
  	ErrorResponse(w, req, http.StatusNotFound, []HttpErrorDesc{
  		{"en", templateHttpErr404_EN},
  		{"rs", templateHttpErr404_RS},
  	})
  }
e1fbb41f9   Marko Tikvić   added comments
131
  // BadRequestResponse writes HTTP error 400 to w.
33fd58161   markotikvic   minor changes, sh...
132
133
  func BadRequestResponse(w http.ResponseWriter, req *http.Request) {
  	ErrorResponse(w, req, http.StatusBadRequest, []HttpErrorDesc{
d2ddf82ef   Marko Tikvić   started on new rbac
134
135
  		{"en", templateHttpErr400_EN},
  		{"rs", templateHttpErr400_RS},
25e001550   Marko Tikvić   exported everything
136
  	})
64041a2ea   Marko Tikvić   first commit
137
  }
e1fbb41f9   Marko Tikvić   added comments
138
  // InternalSeverErrorResponse writes HTTP error 500 to w.
33fd58161   markotikvic   minor changes, sh...
139
140
  func InternalServerErrorResponse(w http.ResponseWriter, req *http.Request) {
  	ErrorResponse(w, req, http.StatusInternalServerError, []HttpErrorDesc{
d2ddf82ef   Marko Tikvić   started on new rbac
141
142
  		{"en", templateHttpErr500_EN},
  		{"rs", templateHttpErr500_RS},
25e001550   Marko Tikvić   exported everything
143
  	})
64041a2ea   Marko Tikvić   first commit
144
  }
e1fbb41f9   Marko Tikvić   added comments
145
  // UnauthorizedError writes HTTP error 401 to w.
33fd58161   markotikvic   minor changes, sh...
146
  func UnauthorizedResponse(w http.ResponseWriter, req *http.Request) {
bc3671b26   Marko Tikvić   refactoring token...
147
  	w.Header().Set("WWW-Authenticate", "Bearer")
33fd58161   markotikvic   minor changes, sh...
148
  	ErrorResponse(w, req, http.StatusUnauthorized, []HttpErrorDesc{
d2ddf82ef   Marko Tikvić   started on new rbac
149
150
  		{"en", templateHttpErr401_EN},
  		{"rs", templateHttpErr401_RS},
33fd58161   markotikvic   minor changes, sh...
151
152
  	})
  }