ตัวอย่างการทำ Http Request Golang


Require

- github.com/labstack/echo/v4 # framework api golang

Begin

$ go mod init <project>

Import library

import (
    "encoding/json"
    "net/http"
    "github.com/labstack/echo/v4"
)

Function Get Api

func GetCaseToday(c echo.Context) error {
    var url = "https://covid19.th-stat.com/api/open/today"
    resp, err := http.Get(url)
    if err != nil {
        print(err)
    }

    var result map[string]interface{}
    json.NewDecoder(resp.Body).Decode(&result)

    return c.JSON(200, result)
}

เป็น Funtion สำหรับ ดึงข้อมูล มาแสดง

Function Main

func main() {
    e := echo.New()
    e.GET("/casetoday", GetCaseToday)
    e.Logger.Fatal(e.Start(":1323"))
}

All

package main

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

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

func GetCaseToday(c echo.Context) error {
    var url = "https://covid19.th-stat.com/api/open/today"
    resp, err := http.Get(url)
    if err != nil {
        print(err)
    }

    var result map[string]interface{}
    json.NewDecoder(resp.Body).Decode(&result)

    return c.JSON(200, result)
}

func main() {
    e := echo.New()
    e.GET("/casetoday", GetCaseToday)
    e.Logger.Fatal(e.Start(":1323"))
}

Run

$ go run .

ลอง Curl


  • Source

jaedsadadotme/http-request

August 2, 2020