Created
December 2, 2025 10:15
-
-
Save aminnairi/dcd306c87436cc2916ce65625ee86c73 to your computer and use it in GitHub Desktop.
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 ( | |
| "crypto/rand" | |
| "encoding/base64" | |
| "encoding/json" | |
| "fmt" | |
| "log" | |
| "net/http" | |
| "golang.org/x/crypto/bcrypt" | |
| ) | |
| type SigninRequest struct { | |
| Email string `json:"email"` | |
| Password string `json:"password"` | |
| } | |
| type SigninResponse struct { | |
| Success bool `json:"success"` | |
| Message string `json:"message"` | |
| Token string `json:"token"` | |
| } | |
| type User struct { | |
| Email string | |
| Password string | |
| } | |
| func main() { | |
| user := User{ | |
| Email: "[email protected]", | |
| Password: "$2y$10$Q4W1ewsTLmvX20lLwKn/..jBIqsxiVrkt5wi/vnE3hjA4R/Uz6SKW", | |
| } | |
| http.HandleFunc("POST /signin", func(response http.ResponseWriter, request *http.Request) { | |
| signinRequest := SigninRequest{} | |
| decodeError := json.NewDecoder(request.Body).Decode(&signinRequest) | |
| if decodeError != nil { | |
| fmt.Fprintln(response, "Decoding request has failed because", decodeError) | |
| return | |
| } | |
| response.WriteHeader(http.StatusOK) | |
| response.Header().Add("Content-Type", "application/json") | |
| compareError := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(signinRequest.Password)) | |
| bytes := make([]byte, 32) | |
| _, readError := rand.Read(bytes) | |
| if readError != nil { | |
| response.WriteHeader(http.StatusInternalServerError) | |
| response.Header().Set("Content-Type", "text/plain") | |
| fmt.Fprintln(response, "Unable to generate enough entropy") | |
| return | |
| } | |
| token := base64.RawURLEncoding.EncodeToString(bytes) | |
| signinResponse := SigninResponse{ | |
| Success: true, | |
| Message: "All checked", | |
| Token: token, | |
| } | |
| if compareError != nil { | |
| signinResponse.Success = false | |
| signinResponse.Message = "Bad credentials" | |
| } | |
| encodeError := json.NewEncoder(response).Encode(signinResponse) | |
| if encodeError != nil { | |
| response.WriteHeader(http.StatusInternalServerError) | |
| response.Header().Set("Content-Type", "text/plain") | |
| fmt.Fprintln(response, "Cannot encode response because", encodeError) | |
| } | |
| }) | |
| fmt.Println("Démarrage du serveur...") | |
| address := ":8080" | |
| listenError := http.ListenAndServe(address, nil) | |
| if listenError != nil { | |
| log.Fatal("Erreur, le serveur n'a pas démarré : ", listenError) | |
| } | |
| fmt.Println("Hello, ESGI!") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment