package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"time"
)
const BaseURI = "https://hyperhuman.deemos.com/api"
var client = &http.Client{Timeout: 10 * time.Second}
type CommonError struct {
Error *string `json:"error,omitempty"`
}
type UserBasicInformation struct {
UserUUID string `json:"user_uuid,omitempty"`
Username string `json:"username,omitempty"`
AvatarUrl string `json:"avatar_url,omitempty"`
Email string `json:"email,omitempty"`
}
// RegisterResponse represents the response from the Register endpoint.
type RegisterResponse struct {
CommonError
UserBasicInformation
Token string `json:"token,omitempty"`
}
// SendEmailVerification sends an email verification code for the specified action type.
func SendEmailVerification(email, actionType string) error {
payload := map[string]string{"email": email, "type": actionType}
jsonData, err := json.Marshal(payload)
if err != nil {
return err
}
req, err := http.NewRequest("POST", fmt.Sprintf("%s/user/send_email_verification_code", BaseURI), bytes.NewBuffer(jsonData))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
var responseData CommonError
err = json.NewDecoder(resp.Body).Decode(&responseData)
if err != nil {
return err
}
if responseData.Error != nil {
return fmt.Errorf("error: %s", *responseData.Error)
}
return nil
}
// Register performs account registration.
func Register(username, email, code, password string) (string, *UserBasicInformation, error) {
payload := map[string]string{"username": username, "email": email, "email_verification_code": code, "password": password}
jsonData, err := json.Marshal(payload)
if err != nil {
return "", nil, err
}
req, err := http.NewRequest("POST", fmt.Sprintf("%s/user/register", BaseURI), bytes.NewBuffer(jsonData))
if err != nil {
return "", nil, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
return "", nil, err
}
defer resp.Body.Close()
var responseData RegisterResponse
err = json.NewDecoder(resp.Body).Decode(&responseData)
if err != nil {
return "", nil, err
}
if responseData.Error != nil {
return "", nil, fmt.Errorf("error: %s", *responseData.Error)
}
return responseData.Token, &responseData.UserBasicInformation, nil
}
func main() {
email := "[email protected]"
err := SendEmailVerification(email, "Register")
if err != nil {
fmt.Printf("Error sending email verification: %s\n", err)
return
}
username := "<your username>"
code := "000000"
password := "<your password>"
token, info, err := Register(username, email, code, password)
if err != nil {
fmt.Printf("Error registering user: %s\n", err)
return
}
fmt.Println("Registered in successfully. Token:", token, "BasicInformation:", *info)
}