Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

http
golang

How to use the HTTP Client in GO

Educative Answers Team

HTTP Client

The http package in GoLang allows HTTP functions to be carried out in GoLang scripts.

Usage

To use HTTP commands in GO, the net/http package needs to be imported. The following example shows how to get a website using GO:

package main
import "fmt"
import "net/http"
func main() {
    resp, err := http.Get("http://educative.io")
    if err == nil {
        fmt.Println(resp.Status)
        defer resp.Body.Close()
    } else {
        panic(err)
    }
    
    resp, err = http.Get("http://invalidurl.com")
    if err == nil {
        fmt.Println(resp.Status)
        defer resp.Body.Close()
    } else {
        panic(err)
    }
}

The Get() function attempts to get the specified webpage through an HTTP connection. The first website is successfully received and a 200 OK status is displayed as an indication. However, when an invalid URL is attempted, the error message 404 Not Found is displayed. As a good practice, the response body, which contains the HTML of the requested website, should be closed before the program is exited.

A more useful application of this HTTP client would be as an HTTP server. The following example displays a very simplified server.

func educative (w http.ResponseWriter, req *http.Request){
  fmt.Fprintf(w, "Response")
}

func main() {
  http.HandleFunc("/educative", educative)

  http.ListenAndServe(":9090", nil)
}

This code sets up a server at port 9090 using the ListenAndServe() function. The HandleFunc() function sets the educative() function to handle all HTTP requests with /educative in the URL. All handler functions need to have an http.ResponseWriter and *http.Request in their arguments. The Response Writer can then be used, as it has been here, to send a response. The handler function here simply sends the word “Response” as a reply. In real servers, one would expect some real data, some HTML, or other files to be returned as a response.

RELATED TAGS

http
golang
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring