Installလုပ်တဲ့အခါ userကို authorizeလုပ်ဖို ဘယ်ဆိုတောင်းဆိုရမလဲ golangကိုသုံးပီး example codeထုတ်ပေးနိုင်မလား
ဟုတ်ကဲ့၊ Golang ကိုသုံးပြီး user authorization လုပ်တဲ့ example code ကို ပြပေးပါမယ်။ ဒီ example မှာ OAuth2 protocol ကို အသုံးပြုထားပါတယ်။
package main
import (
"fmt"
"log"
"net/http"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
var (
googleOauthConfig = &oauth2.Config{
RedirectURL: "http://localhost:8080/callback",
ClientID: "your-client-id",
ClientSecret: "your-client-secret",
Scopes: []string{"https://www.googleapis.com/auth/userinfo.email"},
Endpoint: google.Endpoint,
}
// Some random string, random enough to not be guessable
oauthStateString = "random"
)
func main() {
http.HandleFunc("/", handleMain)
http.HandleFunc("/login", handleGoogleLogin)
http.HandleFunc("/callback", handleGoogleCallback)
fmt.Println("Started server on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func handleMain(w http.ResponseWriter, r *http.Request) {
var htmlIndex = `<html><body><a href="/login">Log in with Google</a></body></html>`
fmt.Fprintf(w, htmlIndex)
}
func handleGoogleLogin(w http.ResponseWriter, r *http.Request) {
url := googleOauthConfig.AuthCodeURL(oauthStateString)
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
func handleGoogleCallback(w http.ResponseWriter, r *http.Request) {
state := r.FormValue("state")
if state != oauthStateString {
fmt.Printf("invalid oauth state, expected '%s', got '%s'\n", oauthStateString, state)
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
code := r.FormValue("code")
token, err := googleOauthConfig.Exchange(oauth2.NoContext, code)
if err != nil {
fmt.Printf("Code exchange failed with '%s'\n", err)
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
fmt.Fprintf(w, "Authentication successful! Access token: %s\n", token.AccessToken)
}
ဒီ code မှာ:
- User က "/login" ကို click လုပ်တဲ့အခါ Google OAuth login page ကို redirect လုပ်ပါတယ်။
- User က login လုပ်ပြီးတဲ့အခါ Google က "/callback" ကို redirect လုပ်ပါတယ်။
- Callback function က authorization code ကို access token နဲ့ exchange လုပ်ပါတယ်။
ဒီ code ကို run ဖို့ အရင်ဆုံး Google Cloud Console မှာ OAuth 2.0 client ID တစ်ခု create လုပ်ရပါမယ်။ ပြီးရင် ClientID နဲ့ ClientSecret ကို code ထဲမှာ replace လုပ်ရပါမယ်။
ဒါဟာ basic example တစ်ခုဖြစ်ပါတယ်။ real-world application တွေမှာ token ကို store လုပ်တာ၊ user information ကို fetch လုပ်တာ စတာတွေ ထပ်လုပ်ရပါမယ်။