Huy
Huy

Reputation: 11206

Go App works but within Docker - unexpected end of JSON input

I have the following controller that makes an external API call using a wrapper built in Go. The issue is that if I run my server without docker, the endpoint returns valid data. However, the moment I run it from within docker, the error I get is unexpected end of JSON input.

home.go

package controllers

import (
  "fmt"
  "encoding/json"

  "net/http"
  "time"
  "strconv"

  cmc "github.com/coincircle/go-coinmarketcap"
)

type HomeController struct{}

func NewHomeController() *HomeController {
  return &HomeController{}
}

func (hc HomeController) IndexEndpoint(w http.ResponseWriter, r *http.Request) {
  threeMonths := int64(60 * 60 * 24 * 90)
  now := time.Now()
  secs := now.Unix()
  start := secs - threeMonths
  end := secs

  fmt.Println("Time is " + strconv.FormatInt(end, 10))

  graph, _ := cmc.TickerGraph(&cmc.TickerGraphOptions{
    Start: start,
    End: end,
    Symbol: "ETH",
  })

  fmt.Println(graph)

  w.Header().Set("Access-Control-Allow-Origin", "*")
  w.Header().Set("Content-Type", "application/json")
  w.WriteHeader(http.StatusCreated)

  json.NewEncoder(w).Encode(graph)
}

Here is my docker setup:

Dockerfile

FROM golang:latest AS builder

COPY . $GOPATH/src/github.com/gohuygo/cryptodemo-api
WORKDIR $GOPATH/src/github.com/gohuygo/cryptodemo-api

RUN go get ./

RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix nocgo -o /app .

FROM scratch
COPY --from=builder /app ./
ENTRYPOINT ["./app"]

Why is it complaining about bad json when docker is involved (i.e. how do I fix this)?

Thanks

Upvotes: 1

Views: 1336

Answers (1)

Michael Hampton
Michael Hampton

Reputation: 10000

Your go application probably attempts to make outgoing HTTPS connections, but the scratch container doesn't include CA certificates necessary to verify TLS certificates.

Consider using centurylink/ca-certs instead of scratch in this circumstance. It includes CA certificates and your program should use them automatically.

Upvotes: 3

Related Questions