package main import ( "bufio" "encoding/json" "fmt" "io" "log" "net/http" "net/url" "os" ) type app struct { ClientId string `json:"client_id"` ClientSecret string `json:"client_secret"` } type user struct { Username string `json:"username"` Instance string `json:"instance"` AccessToken string `json:"access_token"` } var BASE_URL = "https://awoo.fai.st" var DEFAULT_REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob" func main() { // Get the `client_id` and the `client_secret` values app, err := getAppCredentials(BASE_URL) if err != nil { log.Fatal(err) } fmt.Println(getTokenUrl(BASE_URL, app)) // Read the token fmt.Print("Enter token: ") reader := bufio.NewReader(os.Stdin) token, err := reader.ReadString('\n') if err != nil { log.Fatal(err) } token = token[:len(token)-1] fmt.Println(token) } func getTokenUrl(instance string, app *app) string { return fmt.Sprintf("%s/oauth/authorize?response_type=code&client_id=%s&redirect_uri=%s", BASE_URL, app.ClientId, DEFAULT_REDIRECT_URI) } func getAppCredentials(instance string) (*app, error) { // We try to read the file `credentials.json` to read // the application's credentials // If it doesn't exist, we generate a new application contents, err := os.ReadFile("credentials.json") if err != nil { return createApp(instance) } // The file's contents are unmarshalled into a map var credentials app err = json.Unmarshal(contents, &credentials) if err != nil { return nil, err } return &credentials, nil } func createApp(instance string) (*app, error) { // Define the values to the request for creating the app data := url.Values{ "client_name": {"grames"}, "redirect_uris": {DEFAULT_REDIRECT_URI}, } // Send request to create app resp, err := http.PostForm(instance+"/api/v1/apps", data) if err != nil { return nil, err } defer resp.Body.Close() // Read the body's JSON response into `contents` as []byte contents, err := io.ReadAll(resp.Body) if err != nil { return nil, err } // Unmarshal the JSON data into an app struct var credentials app err = json.Unmarshal(contents, &credentials) if err != nil { return nil, err } // Marshal the app into JSON data b, err := json.MarshalIndent(credentials, "", " ") if err != nil { return nil, err } // Write the JSON data into the file `credentials.json` err = os.WriteFile("credentials.json", b, 0644) if err != nil { return nil, err } return &credentials, nil }