Skip to content

Commit

Permalink
Introduce an API endpoint to exchange username to correctly-cased use…
Browse files Browse the repository at this point in the history
…rname and uuid
  • Loading branch information
erickskrauch committed Sep 22, 2024
1 parent 5c84a47 commit 8fbd295
Showing 1 changed file with 38 additions and 2 deletions.
40 changes: 38 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"io"
Expand Down Expand Up @@ -67,7 +68,12 @@ func main() {
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(10)

findAccountByUuidStmt, err := db.Prepare("SELECT username FROM accounts WHERE uuid = ? LIMIT 1")
findUsernameByUuidStmt, err := db.Prepare("SELECT username FROM accounts WHERE uuid = ? LIMIT 1")
if err != nil {
panic(fmt.Errorf("unable to prepare query: %w", err))
}

findUuidAndCorrectUsernameByUsernameStmt, err := db.Prepare("SELECT uuid, username FROM accounts WHERE username = ? LIMIT 1")
if err != nil {
panic(fmt.Errorf("unable to prepare query: %w", err))
}
Expand All @@ -85,7 +91,7 @@ func main() {
}

var username string
err = findAccountByUuidStmt.QueryRow(uuid).Scan(&username)
err = findUsernameByUuidStmt.QueryRow(uuid).Scan(&username)
if errors.Is(err, sql.ErrNoRows) {
response.WriteHeader(204)
return
Expand Down Expand Up @@ -124,6 +130,36 @@ func main() {
return
}
}))
router.GET("/api/mojang/profiles/:username", logRequestHandler(func(
response http.ResponseWriter,
request *http.Request,
params httprouter.Params,
) {
var username, uuid string
err = findUuidAndCorrectUsernameByUsernameStmt.QueryRow(params.ByName("username")).Scan(&uuid, &username)
if errors.Is(err, sql.ErrNoRows) {
response.WriteHeader(204)
return
} else if err != nil {
panic(err)
}

response.Header().Set("Content-Type", "application/json")
response.WriteHeader(http.StatusOK)

result, err := json.Marshal(map[string]string{
"id": strings.ReplaceAll(uuid, "-", ""),
"name": username,
})

_, err = response.Write(result)
if err != nil {
sentry.CaptureException(fmt.Errorf("unable to write response body: %w", err))
response.WriteHeader(500)

return
}
}))

err = http.ListenAndServe(fmt.Sprintf("%s:%d", viper.GetString("http.host"), viper.GetInt("http.port")), router)
if err != nil {
Expand Down

0 comments on commit 8fbd295

Please sign in to comment.