Created
March 14, 2021 16:10
-
-
Save lucasguiss/28a76076cad365b2970c9f569dd2cbb7 to your computer and use it in GitHub Desktop.
Go endpoint that converts a given message to a custom response to present on a Chapter to ROIT INNOVATION
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"log" | |
"net/http" | |
"time" | |
"github.com/gorilla/mux" | |
) | |
type StandardResponse struct { | |
Status string `json:"status"` | |
Data DataResponse `json:"data"` | |
Timestamp int64 `json:"timestamp"` | |
} | |
type DataResponse struct { | |
Message string `json:"message"` | |
} | |
type Payload struct { | |
Message string | |
} | |
func ConvertMessage(w http.ResponseWriter, r *http.Request) { | |
var response StandardResponse | |
var payload Payload | |
timestamp := time.Now().Unix() | |
err := json.NewDecoder(r.Body).Decode(&payload) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
return | |
} | |
response.Timestamp = timestamp | |
response.Data.Message = payload.Message | |
response.Status = "SUCESSO" | |
resp, err := json.Marshal(response) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
} | |
w.Write([]byte(resp)) | |
} | |
func main() { | |
router := mux.NewRouter() | |
router.HandleFunc("/", ConvertMessage).Methods("POST") | |
log.Println("Server ouvindo na porta 3000") | |
log.Fatal(http.ListenAndServe(":3000", router)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment