Created
February 7, 2024 22:26
-
-
Save cheikhsimsol/24bfee2d501e1cec836f99de8b1ac736 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"io" | |
"log" | |
"net/http" | |
"golang.org/x/oauth2" | |
) | |
func main() { | |
mux := http.NewServeMux() | |
conf := &oauth2.Config{ | |
ClientID: "RANDOM", | |
ClientSecret: "RANDOM", | |
Scopes: []string{"offline_access"}, | |
Endpoint: oauth2.Endpoint{ | |
TokenURL: "https://oauth.wiremockapi.cloud/oauth/token", | |
AuthURL: "https://oauth.wiremockapi.cloud/oauth/authorize", | |
}, | |
RedirectURL: "http://localhost:8080/consume", | |
} | |
// Map a route to handle requests to the root path ("/") | |
mux.HandleFunc("GET /login", func(w http.ResponseWriter, r *http.Request) { | |
// section to redirect user | |
url := conf.AuthCodeURL("state", oauth2.AccessTypeOffline) | |
http.Redirect(w, r, url, http.StatusTemporaryRedirect) | |
}) | |
mux.HandleFunc("GET /consume", func(w http.ResponseWriter, r *http.Request) { | |
ctx := context.Background() | |
code := r.FormValue("code") | |
state := r.FormValue("state") | |
if state != "state" { | |
log.Fatal("Wrong state passed") | |
} | |
tok, err := conf.Exchange(ctx, code) | |
if err != nil { | |
log.Fatal(err) | |
} | |
client := conf.Client(ctx, tok) | |
res, err := client.Get("https://oauth.wiremockapi.cloud/userinfo") | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer res.Body.Close() | |
// Set the content type based on the response header | |
w.Header().Set("Content-Type", res.Header.Get("Content-Type")) | |
// Copy the response body to the client's response writer | |
_, err = io.Copy(w, res.Body) | |
if err != nil { | |
http.Error(w, "Error streaming data", http.StatusInternalServerError) | |
return | |
} | |
}) | |
// Create a server using the default ServeMux | |
server := &http.Server{ | |
Addr: ":8080", // Set the server address and port | |
Handler: mux, // Use the custom ServeMux | |
} | |
// Start the server | |
fmt.Println("Server is listening on http://localhost:8080") | |
err := server.ListenAndServe() | |
if err != nil { | |
fmt.Println("Error:", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment