card-jong-be/main.go

76 lines
1.4 KiB
Go
Raw Normal View History

2024-05-03 15:59:20 +00:00
package main
import (
2024-05-08 12:25:52 +00:00
"encoding/json"
2024-05-03 15:59:20 +00:00
"fmt"
"log"
"net/http"
"os"
"github.com/gorilla/mux"
2024-05-08 12:25:52 +00:00
"github.com/nrednav/cuid2"
2024-05-03 15:59:20 +00:00
"github.com/rs/cors"
)
2024-05-08 12:25:52 +00:00
type PersonInfo struct {
UserId string
Username string
}
var users map[string]string
2024-05-03 15:59:20 +00:00
func main() {
fmt.Println("hello SEKAI!!")
router := mux.NewRouter().PathPrefix("/api").Subrouter()
2024-05-08 12:25:52 +00:00
// initialize the global users map
users = make(map[string]string)
2024-05-03 15:59:20 +00:00
router.HandleFunc("/register", Register)
port, ok := os.LookupEnv("PORT")
if !ok {
port = "8080"
}
cors := cors.New(cors.Options{
AllowedOrigins: []string{"http://localhost:3000"},
AllowedMethods: []string{"GET", "DELETE", "POST", "PUT", "OPTIONS"},
AllowedHeaders: []string{"Content-Type", "Origin", "Accept", "Authorization"},
AllowCredentials: true,
})
handler := cors.Handler(router)
log.Fatal(http.ListenAndServe(":"+port, handler))
}
func Register(writer http.ResponseWriter, request *http.Request) {
2024-05-08 12:25:52 +00:00
username := "ga"
uid := cuid2.Generate()
// Store in the users map
users[uid] = username
// The result json
result := PersonInfo{
UserId: uid,
Username: username,
}
2024-05-03 15:59:20 +00:00
writer.Header().Set("Content-Type", "application/json")
2024-05-08 12:25:52 +00:00
jsonData, err := json.Marshal(result)
if err != nil {
fmt.Printf("Error in JSON marshal: %s\n", err)
writer.WriteHeader(http.StatusInternalServerError)
fmt.Printf("{\"error\": \"%s\"}", err)
return
}
2024-05-03 15:59:20 +00:00
writer.WriteHeader(http.StatusOK)
2024-05-08 12:25:52 +00:00
fmt.Fprintf(writer, "%s", jsonData)
2024-05-03 15:59:20 +00:00
}