การใช้งาน API ด้วย Go (Go 1.23)

ตัวอย่างด้านล่างแสดงการใช้งาน API ผ่าน Go สี่รูปแบบ:

ใช้ปุ่มด้านล่างเพื่อสลับดูโค้ดตัวอย่าง

Environment:

1. ขอรับ Token (refresh-token และ access-token)

เริ่มด้วยการขอรับ refresh-token และ access-token โดยใช้ username, password

Go: ตัวอย่างการใช้ไลบรารีมาตรฐาน (net/http) ในการขอ token โดยตรง

Gin: ใช้ Gin จัดการ endpoint /get-tokens เพื่อรับ username/password ผ่าน query parameter และขอ token

Echo: ใช้ Echo จัดการ endpoint /get-tokens เพื่อขอ token

Fiber: ใช้ Fiber จัดการ endpoint /get-tokens เพื่อขอ token

main.go (Go)

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "net/http"
)

func main() {
    data := map[string]string{
        "username": "your_username",
        "password": "your_password",
    }

    jsonData, _ := json.Marshal(data)
    resp, err := http.Post("https://hcode.moph.go.th/api/token/", "application/json", bytes.NewBuffer(jsonData))
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    var tokens map[string]string
    if err := json.NewDecoder(resp.Body).Decode(&tokens); err != nil {
        panic(err)
    }

    fmt.Println("Refresh Token:", tokens["refresh"])
    fmt.Println("Access Token:", tokens["access"])
}
main.go (Gin)

package main

import (
    "bytes"
    "encoding/json"
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    r.POST("/get-tokens", func(c *gin.Context) {
        username := c.DefaultQuery("username", "your_username")
        password := c.DefaultQuery("password", "your_password")

        data := map[string]string{"username": username, "password": password}
        jsonData, _ := json.Marshal(data)

        resp, err := http.Post("https://hcode.moph.go.th/api/token/", "application/json", bytes.NewBuffer(jsonData))
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        defer resp.Body.Close()

        var tokens map[string]string
        if err := json.NewDecoder(resp.Body).Decode(&tokens); err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }

        c.JSON(http.StatusOK, tokens)
    })

    r.Run(":8080")
}
main.go (Echo)

package main

import (
    "bytes"
    "encoding/json"
    "net/http"

    "github.com/labstack/echo/v4"
)

func main() {
    e := echo.New()

    e.POST("/get-tokens", func(c echo.Context) error {
        username := c.QueryParam("username")
        if username == "" {
            username = "your_username"
        }
        password := c.QueryParam("password")
        if password == "" {
            password = "your_password"
        }

        data := map[string]string{"username": username, "password": password}
        jsonData, _ := json.Marshal(data)

        resp, err := http.Post("https://hcode.moph.go.th/api/token/", "application/json", bytes.NewBuffer(jsonData))
        if err != nil {
            return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
        }
        defer resp.Body.Close()

        var tokens map[string]string
        if err := json.NewDecoder(resp.Body).Decode(&tokens); err != nil {
            return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
        }

        return c.JSON(http.StatusOK, tokens)
    })

    e.Logger.Fatal(e.Start(":8080"))
}
main.go (Fiber)

package main

import (
    "bytes"
    "encoding/json"
    "net/http"

    "github.com/gofiber/fiber/v2"
)

func main() {
    app := fiber.New()

    app.Post("/get-tokens", func(c *fiber.Ctx) error {
        username := c.Query("username", "your_username")
        password := c.Query("password", "your_password")

        data := map[string]string{"username": username, "password": password}
        jsonData, _ := json.Marshal(data)

        resp, err := http.Post("https://hcode.moph.go.th/api/token/", "application/json", bytes.NewBuffer(jsonData))
        if err != nil {
            return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
        }
        defer resp.Body.Close()

        var tokens map[string]string
        if err := json.NewDecoder(resp.Body).Decode(&tokens); err != nil {
            return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
        }

        return c.JSON(tokens)
    })

    app.Listen(":8080")
}

2. ทดสอบรับ Tokens โดยตรง

รันโค้ดหรือเรียก endpoint ข้างต้นเพื่อรับ token


3. ขอ Access-Token ใหม่เมื่อ Access-Token หมดอายุ

ใช้ refresh-token เพื่อขอ access-token ใหม่

Go: ตัวอย่างการใช้ refresh-token ใน Go (ไลบรารีมาตรฐาน)

Gin: เพิ่ม endpoint ใน Gin เพื่อต่ออายุ Access-Token ด้วย refresh-token

Echo: เพิ่ม endpoint ใน Echo เพื่อต่ออายุ Access-Token ด้วย refresh-token

Fiber: เพิ่ม endpoint ใน Fiber เพื่อต่ออายุ Access-Token ด้วย refresh-token

refresh.go (Go)

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "net/http"
)

func main() {
    refreshToken := "your_refresh_token_here"

    data := map[string]string{"refresh": refreshToken}
    jsonData, _ := json.Marshal(data)

    resp, err := http.Post("https://hcode.moph.go.th/api/token/refresh/", "application/json", bytes.NewBuffer(jsonData))
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    var result map[string]string
    if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
        panic(err)
    }

    fmt.Println("New Access Token:", result["access"])
}

สรุป: