Skip to content

Instantly share code, notes, and snippets.

@lucasguiss
Created March 14, 2021 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucasguiss/28a76076cad365b2970c9f569dd2cbb7 to your computer and use it in GitHub Desktop.
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
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