Go言語でhttpアクセスするサンプル

jsonを返すだけのサーバー

package main

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

type ColorGroup struct {
	ID     int
	Name   string
	Colors []string
}

func handler(w http.ResponseWriter, r *http.Request) {
	group := ColorGroup{
		ID:     1,
		Name:   "Reds",
		Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
	}
	b, _ := json.Marshal(group)
	fmt.Fprintf(w, string(b))
}

func main() {
	http.HandleFunc("/", handler)
	http.ListenAndServe(":8080", nil)
}


クライアント

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
)

func main() {
	response, err := http.Get("http://localhost:8080")
	if err != nil {
		os.Exit(2)
	}

	fmt.Println(response.Status)
	// -> 200 OK
	fmt.Println(response.StatusCode)
	// -> 200

	fmt.Println(response.Header["Content-Type"])
	// -> [text/plain; charset=utf-8]

	b, _ := ioutil.ReadAll(response.Body)
	fmt.Println(string(b))
	// -> {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}

	var data map[string]interface{}
	json.Unmarshal(b, &data)
	fmt.Println(data)
	// -> map[ID:1 Name:Reds Colors:[Crimson Red Ruby Maroon]]
}