DEV Community

Pallat Anchaleechamaikorn
Pallat Anchaleechamaikorn

Posted on

6 1

เขียน Go ต่อ Oauth ทุกค่าย

#go

ก่อนหน้านี้เคยสงสัยว่าเวลาไปเขียน Frontend มันจะมี lib ให้ไปยิง Oauth2 กับ Facebook ง่ายๆเลย แล้วถ้าจะเขียนด้วย Go มันจะมี lib ง่ายๆแบบนั้นบ้างไหม

วันนี้ก็หาเจอละครับ มันคือเจ้าตัวนี้ github.com/markbates/goth

โดยในหน้า git จะมีบอกว่ามี example ให้ดูด้วยนะ https://github.com/markbates/goth/blob/v1.68.0/examples

พอเปิดเข้าไปดู โอ้โห ตัวอย่างมันต่อทุกค่ายเลย ผมก็เลยทดลอง Facebook โดยวิธีลองก็แสนจะง่าย ก็ copy เจ้า example มาทั้งไฟล์เลย ซึ่งมันมีแค่ไฟล์เดียวคือ main.go

จากนั้น สิ่งที่มันต้องการก็คือ Facebook App ID กับ App Secret โดยให้เอาไปใส่ในค่า env แบบนี้

FACEBOOK_KEY={Facebook App ID}
FACEBOOK_SECRET={App Secret}
SESSION_SECRET=123
Enter fullscreen mode Exit fullscreen mode

ค่า SESSION_SECRET ใส่อะไรลงไปก็ได้
ส่วนที่หน้า Facebook for Developers ก็ให้ตรวจสอบค่า

App Authentication ว่าอย่าให้มันเป็น Native or desktop app?

จากนั้นก็

go run main.go
Enter fullscreen mode Exit fullscreen mode

เสร็จแล้วมันจะ serve ที่ port :3000 บนเครื่องเรา ก็ทดลองเปิด

http://localhost:3000

จากนั้นก็ไปลองกด Login with Facebook ดูโลด

จบการทดลอง

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs