2017-08-20 03:52:42 +05:30
|
|
|
package http
|
|
|
|
|
|
|
|
import (
|
2020-01-02 02:12:45 +05:30
|
|
|
"encoding/json"
|
2020-01-29 04:04:15 +05:30
|
|
|
"net"
|
2017-08-20 03:52:42 +05:30
|
|
|
"net/http"
|
2020-01-29 04:04:15 +05:30
|
|
|
"time"
|
2017-08-20 03:52:42 +05:30
|
|
|
)
|
|
|
|
|
2020-01-29 04:04:15 +05:30
|
|
|
type Emitter interface {
|
|
|
|
Emit(name string, args ...interface{})
|
|
|
|
}
|
|
|
|
|
|
|
|
func Serve(address string, handler http.Handler) error {
|
|
|
|
listener, err := net.Listen("tcp", address)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
server := &http.Server{
|
|
|
|
ReadTimeout: 5 * time.Second,
|
|
|
|
WriteTimeout: 5 * time.Second,
|
|
|
|
IdleTimeout: 60 * time.Second,
|
|
|
|
MaxHeaderBytes: 1 << 16,
|
|
|
|
Handler: handler,
|
|
|
|
}
|
|
|
|
|
|
|
|
return server.Serve(listener)
|
|
|
|
}
|
|
|
|
|
2020-01-02 02:12:45 +05:30
|
|
|
func NotFound(response http.ResponseWriter, _ *http.Request) {
|
|
|
|
data, _ := json.Marshal(map[string]string{
|
|
|
|
"status": "404",
|
|
|
|
"message": "Not Found",
|
|
|
|
})
|
2017-08-20 03:52:42 +05:30
|
|
|
|
2020-01-02 02:12:45 +05:30
|
|
|
response.Header().Set("Content-Type", "application/json")
|
|
|
|
response.WriteHeader(http.StatusNotFound)
|
|
|
|
_, _ = response.Write(data)
|
2017-08-20 03:52:42 +05:30
|
|
|
}
|
|
|
|
|
2020-01-02 02:12:45 +05:30
|
|
|
func apiBadRequest(resp http.ResponseWriter, errorsPerField map[string][]string) {
|
|
|
|
resp.WriteHeader(http.StatusBadRequest)
|
|
|
|
resp.Header().Set("Content-Type", "application/json")
|
|
|
|
result, _ := json.Marshal(map[string]interface{}{
|
|
|
|
"errors": errorsPerField,
|
|
|
|
})
|
|
|
|
_, _ = resp.Write(result)
|
2017-08-20 03:52:42 +05:30
|
|
|
}
|
|
|
|
|
2020-01-02 02:12:45 +05:30
|
|
|
func apiForbidden(resp http.ResponseWriter, reason string) {
|
|
|
|
resp.WriteHeader(http.StatusForbidden)
|
|
|
|
resp.Header().Set("Content-Type", "application/json")
|
|
|
|
result, _ := json.Marshal(map[string]interface{}{
|
|
|
|
"error": reason,
|
|
|
|
})
|
|
|
|
_, _ = resp.Write(result)
|
2017-08-20 03:52:42 +05:30
|
|
|
}
|
|
|
|
|
2020-01-02 02:12:45 +05:30
|
|
|
func apiNotFound(resp http.ResponseWriter, reason string) {
|
|
|
|
resp.WriteHeader(http.StatusNotFound)
|
|
|
|
resp.Header().Set("Content-Type", "application/json")
|
|
|
|
result, _ := json.Marshal([]interface{}{
|
|
|
|
reason,
|
|
|
|
})
|
|
|
|
_, _ = resp.Write(result)
|
|
|
|
}
|
2017-08-20 03:52:42 +05:30
|
|
|
|
2020-01-02 02:12:45 +05:30
|
|
|
func apiServerError(resp http.ResponseWriter) {
|
|
|
|
resp.WriteHeader(http.StatusInternalServerError)
|
2017-08-20 03:52:42 +05:30
|
|
|
}
|