Avatar ·

How to make an HTTPS request in Go with a self-signed or invalid certificate?

Hello everyone! I'm new to Go and working on a project where I need to send HTTPS requests to an internal development server. The problem is that this server uses a self-signed SSL certificate, and Go by default rejects such connections with the error x509: certificate signed by unknown authority.

My current code looks like this:

package main

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

func main() {
    resp, err := http.Get("https://internal-dev.example.com/api/data")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    defer resp.Body.Close()
    
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))
}

I understand that for production this is bad practice