|
| 1 | +package wg |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + |
| 6 | + "log" |
| 7 | + "net/http" |
| 8 | + |
| 9 | + "waitgreen/modules/config" |
| 10 | + |
| 11 | + "github.com/uzhinskiy/lib.go/helpers" |
| 12 | +) |
| 13 | + |
| 14 | +type WaitGreen struct { |
| 15 | + conf config.Config |
| 16 | +} |
| 17 | + |
| 18 | +type apiRequest struct { |
| 19 | + WaitGreen bool `json:"waitgreen"` |
| 20 | +} |
| 21 | + |
| 22 | +var wgEnabled bool |
| 23 | + |
| 24 | +func Run(cnf config.Config) { |
| 25 | + wg := WaitGreen{} |
| 26 | + wg.conf = cnf |
| 27 | + |
| 28 | + wgEnabled = cnf.App.DefaultWG |
| 29 | + |
| 30 | + http.HandleFunc("/", wg.ApiHandler) |
| 31 | + http.ListenAndServe(cnf.App.Bind+":"+cnf.App.Port, nil) |
| 32 | +} |
| 33 | + |
| 34 | +func (wg *WaitGreen) ApiHandler(w http.ResponseWriter, r *http.Request) { |
| 35 | + var request apiRequest |
| 36 | + |
| 37 | + defer r.Body.Close() |
| 38 | + remoteIP := helpers.GetIP(r.RemoteAddr, r.Header.Get("X-Real-IP"), r.Header.Get("X-Forwarded-For")) |
| 39 | + |
| 40 | + w.Header().Add("Access-Control-Allow-Origin", "*") |
| 41 | + w.Header().Add("Access-Control-Allow-Methods", "POST,OPTIONS,GET") |
| 42 | + w.Header().Add("Access-Control-Allow-Credentials", "true") |
| 43 | + w.Header().Add("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization") |
| 44 | + w.Header().Add("Content-Type", "application/json; charset=utf-8") |
| 45 | + w.Header().Set("X-Server", "wg") |
| 46 | + |
| 47 | + if r.Method == "OPTIONS" { |
| 48 | + return |
| 49 | + } |
| 50 | + |
| 51 | + switch r.Method { |
| 52 | + case http.MethodPost: |
| 53 | + { |
| 54 | + err := json.NewDecoder(r.Body).Decode(&request) |
| 55 | + if err != nil { |
| 56 | + http.Error(w, err.Error(), http.StatusInternalServerError) |
| 57 | + log.Println(remoteIP, "\t", r.Method, "\t", r.URL.Path, "\t", http.StatusInternalServerError, "\t", err.Error()) |
| 58 | + return |
| 59 | + } |
| 60 | + |
| 61 | + wgEnabled = request.WaitGreen |
| 62 | + resp := map[string]interface{}{ |
| 63 | + "status": "Ok", |
| 64 | + } |
| 65 | + j, _ := json.Marshal(resp) |
| 66 | + log.Println(remoteIP, "\t", r.Method, "\t", r.URL.Path, "\t", "200", "\t", r.UserAgent()) |
| 67 | + w.Write(j) |
| 68 | + |
| 69 | + } |
| 70 | + case http.MethodGet: |
| 71 | + { |
| 72 | + resp := map[string]interface{}{ |
| 73 | + "waitgreen": wgEnabled, |
| 74 | + } |
| 75 | + j, _ := json.Marshal(resp) |
| 76 | + log.Println(remoteIP, "\t", r.Method, "\t", r.URL.Path, "\t", "200", "\t", r.UserAgent()) |
| 77 | + w.Write(j) |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | +} |
0 commit comments