Answers for "golang api call example"

Go
1

golang http example

package main

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

type Response struct {
	Message string `json:"message"`
}

func GetRequest(rw http.ResponseWriter, req *http.Request) {
	rw.Header().Add("Content-Type", "application/json")

	if req.Method == "GET" {
		data := Response{Message: "Hello World From - GET"}
		json, _ := json.Marshal(data)
		fmt.Fprint(rw, string(json))
	} else {
		data := Response{Message: "Bad Request"}
		json, _ := json.Marshal(data)
		fmt.Fprint(rw, string(json))
	}
}

func PostRequest(rw http.ResponseWriter, req *http.Request) {
	rw.Header().Add("Content-Type", "application/json")

	if req.Method == "POST" {
		data := Response{Message: "Hello World From - POST"}
		json, _ := json.Marshal(data)
		fmt.Fprint(rw, string(json))
	} else {
		data := Response{Message: "Bad Request"}
		json, _ := json.Marshal(data)
		fmt.Fprint(rw, string(json))
	}
}

func main() {
	http.HandleFunc("/get", GetRequest)
	http.HandleFunc("/post", PostRequest)

	log.Fatal(http.ListenAndServe(":8000", nil))
}
Posted by: Guest on October-06-2021
0

using golang to make api calls

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "os"
)

func main() {
    response, err := http.Get("http://pokeapi.co/api/v2/pokedex/kanto/")

    if err != nil {
        fmt.Print(err.Error())
        os.Exit(1)
    }

    responseData, err := ioutil.ReadAll(response.Body)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(responseData))

}
Posted by: Guest on January-29-2022

Browse Popular Code Answers by Language