Permettre au client web de rechercher unE membre

This commit is contained in:
Victor Lacasse-Beaudoin 2023-05-25 22:07:53 -04:00
parent 719c92a652
commit e585b65565
4 changed files with 188 additions and 5 deletions

View file

@ -70,6 +70,7 @@ var webCmd = &cobra.Command{
// Routes // Routes
e.GET("/", webhandlers.GetIndex) e.GET("/", webhandlers.GetIndex)
e.GET("/membre/", webhandlers.GetMembre)
// Execution // Execution
@ -94,6 +95,12 @@ func init() {
"Remote API server key (config:'web.api.key')") "Remote API server key (config:'web.api.key')")
viper.BindPFlag("web.api.key", webCmd.Flags().Lookup("web-api-key")) viper.BindPFlag("web.api.key", webCmd.Flags().Lookup("web-api-key"))
// web.api.protocol
webCmd.Flags().String(
"web-api-protocol", "http",
"Remote API server protocol (config:'web.api.protocol')")
viper.BindPFlag("web.api.protocol", webCmd.Flags().Lookup("web-api-protocol"))
// web.api.port // web.api.port
webCmd.Flags().Int( webCmd.Flags().Int(
"web-api-port", 1312, "web-api-port", 1312,

116
v4/data/apiclient.go Normal file
View file

@ -0,0 +1,116 @@
package data
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"git.agecem.com/agecem/bottin/v4/models"
)
type ApiClient struct {
Key string
Host string
Port int
Protocol string
}
func NewApiClient(key, host, protocol string, port int) *ApiClient {
return &ApiClient{
Key: key,
Host: host,
Port: port,
Protocol: protocol,
}
}
func (a *ApiClient) Call(method, route string, requestBody io.Reader, useKey bool) (*http.Response, error) {
var response *http.Response
endpoint := fmt.Sprintf("%s://%s:%d%s",
a.Protocol, a.Host, a.Port, route,
)
/*
//TODO
log.Println("endpoint: ", endpoint)
*/
// Create client
client := &http.Client{}
// Create request
request, err := http.NewRequest(method, endpoint, requestBody)
if err != nil {
return response, err
}
if useKey {
if a.Key == "" {
return response, fmt.Errorf("Call to API required a key but none was provided. See --help for instructions on providing an API key.")
}
request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", a.Key))
}
if requestBody != nil {
request.Header.Add("Content-Type", "application/json")
}
// Fetch Request
response, err = client.Do(request)
if err != nil {
return response, err
}
return response, nil
}
func (a *ApiClient) GetMembre(membreID string) (models.Membre, error) {
var getMembreResponse struct {
Message string `json:"message"`
Data struct {
Membre models.Membre `json:"membre"`
} `json:"data"`
}
if membreID == "" {
return getMembreResponse.Data.Membre, errors.New("Veuillez fournir un numéro étudiant à rechercher")
}
//TODO
/*
log.Println("ApiClient.GetMembre received membreID: ", membreID)
*/
response, err := a.Call(http.MethodGet, fmt.Sprintf("/v4/membres/%s", membreID), nil, true)
if err != nil {
return getMembreResponse.Data.Membre, err
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return getMembreResponse.Data.Membre, err
}
if err := json.Unmarshal(body, &getMembreResponse); err != nil {
return getMembreResponse.Data.Membre, err
}
/*
if getMembreResponse.Message != "Read successful" {
return getMembreResponse.Data.Membre, errors.New(getMembreResponse.Message)
}
*/
if getMembreResponse.Data.Membre == *new(models.Membre) {
return getMembreResponse.Data.Membre, fmt.Errorf("Ce numéro étudiant ne correspond à aucunE membre")
}
return getMembreResponse.Data.Membre, nil
}

View file

@ -19,12 +19,19 @@
Entrez manuellement le code à 7 chiffres Entrez manuellement le code à 7 chiffres
</p> </p>
<form action="/membre/"> <form action="/membre" method="get">
<label># <ul>
<input type="text" name="num_etud" id="num_etud" autofocus> <li>
</label> <label for="membre_id">Numéro étudiant:</label>
<button formmethod="get" type="submit">Valider</button> <input type="text" id="membre_id" name="membre_id"/>
</li>
<li class="button">
<button type="submit">Rechercher</button>
</li>
</ul>
</form> </form>
<p class="result">{{ .Result }}</p>
</body> </body>
</html> </html>

View file

@ -1,11 +1,64 @@
package webhandlers package webhandlers
import ( import (
"fmt"
"net/http" "net/http"
"git.agecem.com/agecem/bottin/v4/data"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/spf13/viper"
) )
func GetIndex(c echo.Context) error { func GetIndex(c echo.Context) error {
return c.Render(http.StatusOK, "index-html", nil) return c.Render(http.StatusOK, "index-html", nil)
} }
func GetMembre(c echo.Context) error {
apiClientKey := viper.GetString("web.api.key")
apiClientHost := viper.GetString("web.api.host")
apiClientProtocol := viper.GetString("web.api.protocol")
apiClientPort := viper.GetInt("web.api.port")
/*
log.Printf(`
apiClientKey: %s
apiClientHost: %s
apiClientProtocol: %s
apiClientPort: %d`,
apiClientKey, apiClientHost, apiClientProtocol, apiClientPort,
)
*/
apiClient := data.NewApiClient(apiClientKey, apiClientHost, apiClientProtocol, apiClientPort)
membreID := c.QueryParam("membre_id")
/*
// TODO
log.Printf("Requesting membreID: [%s]", membreID)
*/
membre, err := apiClient.GetMembre(membreID)
if err != nil {
return c.Render(http.StatusBadRequest, "index-html", struct {
Result string
}{
Result: fmt.Sprintln("👎", err.Error()),
})
}
membreResult := fmt.Sprintf(`👍
Membre trouvéE: [%s]`, membre.ID)
if membre.PreferedName != "" {
membreResult = fmt.Sprintf("%s -> %s", membreResult, membre.PreferedName)
} else {
membreResult = fmt.Sprintf("%s -> %s, %s", membreResult, membre.LastName, membre.FirstName)
}
return c.Render(http.StatusOK, "index-html", struct {
Result string
}{
Result: membreResult,
})
}