Solicitud de API de Golang
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
)
type Login struct {
Username string `json:"username"`
Password string `json:"password"`
}
type APIResponse struct {
Stat_Code uint32 `json:"stat_code"`
Stat_Msg string `json:"stat_msg"`
}
func ApiResponse(rw http.ResponseWriter, v *APIResponse) {
result, err := json.Marshal(v)
if err != nil {
log.Fatal(err)
}
rw.Write(result)
}
func main() {
server := http.Server{
Addr: ":3000",
}
http.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Content-Type", "application/json")
payload := Login{}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(body, &payload)
if err != nil {
log.Fatal(err)
}
if payload.Username != "johndoe13" || payload.Password != "qwerty12" {
ApiResponse(rw, &APIResponse{Stat_Code: http.StatusBadRequest, Stat_Msg: "Username or password mismatch"})
defer log.Print("http request error")
return
}
ApiResponse(rw, &APIResponse{Stat_Code: http.StatusOK, Stat_Msg: "Login success"})
defer log.Print("http request success")
})
server.ListenAndServe()
}
Restu Wahyu Saputra