Home > Blockchain >  How do I run my main.go file without having to run them separately outside of the containers?
How do I run my main.go file without having to run them separately outside of the containers?

Time:01-04

I have a main.go file that I use to run an app that starts a server that exposes a port where I can run endpoints from. I was trying to dockerise it and got as far as making working containers that hold the app and the db, but I still seem to have to run go run main.go after running docker-compose up -d.

// present folder structure
.
├── cities.json // holds records of all city names
├── docker-compose.yaml 
├── dockerfile
├── go.mod
├── go.sum
├── localmon.sh // bash script that does a mongoimport to import all records from cities.json into the db
├── main.go
└── README.md

I've been told I may have to either map a volume know where that lives and have it execute. Another option (more complex) is a bash script (or both?)

I'm kind of unsure as to how to go about this or what I'm supposed to do with my compose file and dockerfile as it is at the moment.

version: '3.3'
services:
  db:
    hostname: mongo-test
    container_name: "mongo-test"
    image: mongo
    networks:
      - app_test
    ports: 
        - "8001:27017" 
    #   - "27017:27017"
    env_file: .env
    restart: unless-stopped
    volumes:
      - ".mongodata:/data/db"
  
  app: 
    hostname: app-test
    container_name: "app"
    build: 
      context: .
      dockerfile: dockerfile
    networks:
      - app_test
    ports: 
      - "54321:8080"
      # - "8080:8080"
    restart: unless-stopped
    env_file: .env

networks:
  app_test: {}
FROM golang:1.17.5-alpine3.15

RUN mkdir /app
ADD . /app
WORKDIR /app

# Copies and downloads necessary dependencies
COPY go.mod ./
COPY go.sum ./
RUN go mod download
RUN go build -o main .

# Port 8080 exposed for use
EXPOSE 8080

# Command that starts the container
CMD ["./main"]
env file that holds some DB related stuff for the main.go file to use.

DB_URI=mongodb://mongo-test:8001
CITY_DB=nht_cities
COL_USER=user
COL_CITY=city
USER_AUTH_TOKEN=50dba...
// localmon.sh

#! /bin/bash
mongoimport --host 192.168.0.101  --port 8001 --db nht_cities --collection city --type json --file ./cities.json 

docker-compose logs after running a recent docker-compose up -d

Attaching to mongo-test, app
app    | time="2022-01-03T20:08:52Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:09:02Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:09:13Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:09:24Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:09:34Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:09:45Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:09:55Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:10:06Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:10:17Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:10:27Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:10:38Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:10:48Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
app    | time="2022-01-03T20:10:59Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: mongo-test:8001, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 172.23.0.2:8001: connect: connection refused }, ] }"
... goes on for a bit

mongo-test | {"t":{"$date":"2022-01-03T20:08:42.360 00:00"},"s":"I",  "c":"CONTROL",  "id":23285,   "ctx":"-","msg":"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'"}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.362 00:00"},"s":"I",  "c":"NETWORK",  "id":4915701, "ctx":"main","msg":"Initialized wire specification","attr":{"spec":{"incomingExternalClient":{"minWireVersion":0,"maxWireVersion":13},"incomingInternalClient":{"minWireVersion":0,"maxWireVersion":13},"outgoing":{"minWireVersion":0,"maxWireVersion":13},"isInternalClient":true}}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.362 00:00"},"s":"W",  "c":"ASIO",     "id":22601,   "ctx":"main","msg":"No TransportLayer configured during NetworkInterface startup"}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.362 00:00"},"s":"I",  "c":"NETWORK",  "id":4648601, "ctx":"main","msg":"Implicit TCP FastOpen unavailable. If TCP FastOpen is required, set tcpFastOpenServer, tcpFastOpenClient, and tcpFastOpenQueueSize."}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.363 00:00"},"s":"W",  "c":"ASIO",     "id":22601,   "ctx":"main","msg":"No TransportLayer configured during NetworkInterface startup"}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.363 00:00"},"s":"I",  "c":"REPL",     "id":5123008, "ctx":"main","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationDonorService","ns":"config.tenantMigrationDonors"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.363 00:00"},"s":"I",  "c":"REPL",     "id":5123008, "ctx":"main","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationRecipientService","ns":"config.tenantMigrationRecipients"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.363 00:00"},"s":"I",  "c":"CONTROL",  "id":5945603, "ctx":"main","msg":"Multi threading initialized"}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.364 00:00"},"s":"I",  "c":"CONTROL",  "id":4615611, "ctx":"initandlisten","msg":"MongoDB starting","attr":{"pid":1,"port":27017,"dbPath":"/data/db","architecture":"64-bit","host":"mongo-test"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.364 00:00"},"s":"I",  "c":"CONTROL",  "id":23403,   "ctx":"initandlisten","msg":"Build Info","attr":{"buildInfo":{"version":"5.0.5","gitVersion":"d65fd89df3fc039b5c55933c0f71d647a54510ae","openSSLVersion":"OpenSSL 1.1.1f  31 Mar 2020","modules":[],"allocator":"tcmalloc","environment":{"distmod":"ubuntu2004","distarch":"x86_64","target_arch":"x86_64"}}}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.364 00:00"},"s":"I",  "c":"CONTROL",  "id":51765,   "ctx":"initandlisten","msg":"Operating System","attr":{"os":{"name":"Ubuntu","version":"20.04"}}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.364 00:00"},"s":"I",  "c":"CONTROL",  "id":21951,   "ctx":"initandlisten","msg":"Options set by command line","attr":{"options":{"net":{"bindIp":"*"}}}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.365 00:00"},"s":"I",  "c":"STORAGE",  "id":22270,   "ctx":"initandlisten","msg":"Storage engine to use detected by data files","attr":{"dbpath":"/data/db","storageEngine":"wiredTiger"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.365 00:00"},"s":"I",  "c":"STORAGE",  "id":22297,   "ctx":"initandlisten","msg":"Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem","tags":["startupWarnings"]}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.365 00:00"},"s":"I",  "c":"STORAGE",  "id":22315,   "ctx":"initandlisten","msg":"Opening WiredTiger","attr":{"config":"create,cache_size=7178M,session_max=33000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),builtin_extension_config=(zstd=(compression_level=6)),file_manager=(close_idle_time=600,close_scan_interval=10,close_handle_minimum=250),statistics_log=(wait=0),verbose=[recovery_progress,checkpoint_progress,compact_progress],"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.942 00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1641240522:942716][1:0x7f62a3693c80], txn-recover: [WT_VERB_RECOVERY_PROGRESS] Recovering log 9 through 10"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:42.968 00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1641240522:968493][1:0x7f62a3693c80], txn-recover: [WT_VERB_RECOVERY_PROGRESS] Recovering log 10 through 10"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.010 00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1641240523:10614][1:0x7f62a3693c80], txn-recover: [WT_VERB_RECOVERY_ALL] Main recovery loop: starting at 9/5120 to 10/256"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.056 00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1641240523:56865][1:0x7f62a3693c80], txn-recover: [WT_VERB_RECOVERY_PROGRESS] Recovering log 9 through 10"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.084 00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1641240523:84544][1:0x7f62a3693c80], txn-recover: [WT_VERB_RECOVERY_PROGRESS] Recovering log 10 through 10"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.108 00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1641240523:108553][1:0x7f62a3693c80], txn-recover: [WT_VERB_RECOVERY_ALL] Set global recovery timestamp: (0, 0)"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.108 00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1641240523:108603][1:0x7f62a3693c80], txn-recover: [WT_VERB_RECOVERY_ALL] Set global oldest timestamp: (0, 0)"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.110 00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1641240523:110204][1:0x7f62a3693c80], WT_SESSION.checkpoint: [WT_VERB_CHECKPOINT_PROGRESS] saving checkpoint snapshot min: 1, snapshot max: 1 snapshot count: 0, oldest timestamp: (0, 0) , meta checkpoint timestamp: (0, 0) base write gen: 616"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.115 00:00"},"s":"I",  "c":"STORAGE",  "id":4795906, "ctx":"initandlisten","msg":"WiredTiger opened","attr":{"durationMillis":750}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.115 00:00"},"s":"I",  "c":"RECOVERY", "id":23987,   "ctx":"initandlisten","msg":"WiredTiger recoveryTimestamp","attr":{"recoveryTimestamp":{"$timestamp":{"t":0,"i":0}}}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.116 00:00"},"s":"I",  "c":"STORAGE",  "id":4366408, "ctx":"initandlisten","msg":"No table logging settings modifications are required for existing WiredTiger tables","attr":{"loggingEnabled":true}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.117 00:00"},"s":"I",  "c":"STORAGE",  "id":22262,   "ctx":"initandlisten","msg":"Timestamp monitor starting"}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.120 00:00"},"s":"W",  "c":"CONTROL",  "id":22120,   "ctx":"initandlisten","msg":"Access control is not enabled for the database. Read and write access to data and configuration is unrestricted","tags":["startupWarnings"]}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.123 00:00"},"s":"I",  "c":"NETWORK",  "id":4915702, "ctx":"initandlisten","msg":"Updated wire specification","attr":{"oldSpec":{"incomingExternalClient":{"minWireVersion":0,"maxWireVersion":13},"incomingInternalClient":{"minWireVersion":0,"maxWireVersion":13},"outgoing":{"minWireVersion":0,"maxWireVersion":13},"isInternalClient":true},"newSpec":{"incomingExternalClient":{"minWireVersion":0,"maxWireVersion":13},"incomingInternalClient":{"minWireVersion":13,"maxWireVersion":13},"outgoing":{"minWireVersion":13,"maxWireVersion":13},"isInternalClient":true}}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.123 00:00"},"s":"I",  "c":"STORAGE",  "id":5071100, "ctx":"initandlisten","msg":"Clearing temp directory"}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.123 00:00"},"s":"I",  "c":"CONTROL",  "id":20536,   "ctx":"initandlisten","msg":"Flow Control is enabled on this deployment"}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.124 00:00"},"s":"I",  "c":"FTDC",     "id":20625,   "ctx":"initandlisten","msg":"Initializing full-time diagnostic data capture","attr":{"dataDirectory":"/data/db/diagnostic.data"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.126 00:00"},"s":"I",  "c":"REPL",     "id":6015317, "ctx":"initandlisten","msg":"Setting new configuration state","attr":{"newState":"ConfigReplicationDisabled","oldState":"ConfigPreStart"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.126 00:00"},"s":"I",  "c":"NETWORK",  "id":23015,   "ctx":"listener","msg":"Listening on","attr":{"address":"/tmp/mongodb-27017.sock"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.127 00:00"},"s":"I",  "c":"NETWORK",  "id":23015,   "ctx":"listener","msg":"Listening on","attr":{"address":"0.0.0.0"}}
mongo-test | {"t":{"$date":"2022-01-03T20:08:43.127 00:00"},"s":"I",  "c":"NETWORK",  "id":23016,   "ctx":"listener","msg":"Waiting for connections","attr":{"port":27017,"ssl":"off"}}
mongo-test | {"t":{"$date":"2022-01-03T20:09:43.122 00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"Checkpointer","msg":"WiredTiger message","attr":{"message":"[1641240583:122644][1:0x7f629ae81700], WT_SESSION.checkpoint: [WT_VERB_CHECKPOINT_PROGRESS] saving checkpoint snapshot min: 3, snapshot max: 3 snapshot count: 0, oldest timestamp: (0, 0) , meta checkpoint timestamp: (0, 0) base write gen: 616"}}
mongo-test | {"t":{"$date":"2022-01-03T20:10:43.134 00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"Checkpointer","msg":"WiredTiger message","attr":{"message":"[1641240643:134518][1:0x7f629ae81700], WT_SESSION.checkpoint: [WT_VERB_CHECKPOINT_PROGRESS] saving checkpoint snapshot min: 6, snapshot max: 6 snapshot count: 0, oldest timestamp: (0, 0) , meta checkpoint timestamp: (0, 0) base write gen: 616"}}
mongo-test | {"t":{"$date":"2022-01-03T20:11:43.147 00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"Checkpointer","msg":"WiredTiger message","attr":{"message":"[1641240703:147808][1:0x7f629ae81700], WT_SESSION.checkpoint: [WT_VERB_CHECKPOINT_PROGRESS] saving checkpoint snapshot min: 8, snapshot max: 8 snapshot count: 0, oldest timestamp: (0, 0) , meta checkpoint timestamp: (0, 0) base write gen: 616"}}
package main

import (
    "context"
    "crypto/sha256"
    "encoding/json"
    "fmt"
    "math/rand"
    "net/http"
    "os"
    "time"

    "github.com/gorilla/mux"
    "github.com/joho/godotenv"
    log "github.com/sirupsen/logrus"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/bson/primitive"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "go.mongodb.org/mongo-driver/mongo/readpref"
)

var client mongo.Client                                                                       // mongo client from setup declared globally
var characterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") // character runes used for creation of tokens

func setup() { // Setup for mongodb connection using mongo drivers. Returns client.
    clientOptions := options.Client().
        ApplyURI(os.Getenv("DB_URI"))
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    clientLocal, err := mongo.Connect(ctx, clientOptions)
    if err != nil {
        log.Fatalln(err, "This is from the first one")
    }
    err = clientLocal.Ping(ctx, readpref.Primary())
    if err != nil {
        log.Fatalln(err, "This is from the second one")
    }
    fmt.Println("MongoDB started successfully!")
    client = *clientLocal
}

// model for user endpoint
type User struct {
    Email       string `json:"email"`
    AccessToken string `json:"token"`
}

type City struct {
    Name string `bson:"name" json:"name"`
}

func main() {
    err := godotenv.Load() // Loads environment variables from .env
    if err != nil {
        log.Fatal("Error loading .env file")
    }

    setup()
    r := mux.NewRouter()
    r.Handle("/user", UserAuth(createUser)).Methods("POST")  // Route for registering new users
    r.Handle("/suggest", APIAuth(searchCity)).Methods("GET") // Route for searching cities within DB

    fmt.Println("Server running at port 8080")
    log.Fatal(http.ListenAndServe(":8080", r))

}

func createUser(w http.ResponseWriter, r *http.Request) { // POST request that takes in user details, generates an access token and inserts them into the DB
    w.Header().Add("content-type", "application/json")

    var user User
    _ = json.NewDecoder(r.Body).Decode(&user)
    userCollection := client.Database(os.Getenv("CITY_DB")).Collection(os.Getenv("COL_USER")) // Holds 'user' collection from DB
    user.AccessToken = generateToken()                                                        // Generated access token is assigned to user struct

    _, err := userCollection.InsertOne(context.Background(), user) // Details are inserted into the collection
    if err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        log.Fatalln(err, "Failed to create user.")
    }
    json.NewEncoder(w).Encode(user)

}

func searchCity(w http.ResponseWriter, r *http.Request) { // GET request that takes in a url param and returns a list of cities from the DB
    w.Header().Set("Content-Type", "application/json")

    values := r.URL.Query()
    city := values["city_name"]                                                               // Assigns url param from route `/suggest?city_name=` to 'city'
    cityCollection := client.Database(os.Getenv("CITY_DB")).Collection(os.Getenv("COL_CITY")) // Holds 'city' collection from DB

    if len(city) == 0 {
        w.WriteHeader(http.StatusOK)
        w.Write([]byte(`{"Error": "City name cannot be empty!"}`))
        return
    }

    filter := bson.D{ //Regex filter for querying the input through the DB
        primitive.E{
            Key: "all_names", Value: primitive.Regex{
                Pattern: city[0], Options: "i",
            },
        },
    }

    cursor, err := cityCollection.Find(r.Context(), filter) // Query to find city is declared with cursor
    if err != nil {
        log.Fatal(err)
        w.WriteHeader(http.StatusInternalServerError)
        w.Write([]byte(`{"Error": "Could not execute cursor into query."}`))
        return
    }

    var cityList []City
    for cursor.Next(context.TODO()) { // Runs through each document entry in DB to see if regex matches
        var cities City
        err := cursor.Decode(&cities)
        if err != nil {
            log.Fatal(err)
            w.WriteHeader(http.StatusInternalServerError)
            w.Write([]byte(`{"Error": "Could not run cursor."}`))
            return
        }
        cityList = append(cityList, cities) // List of cities is appended to cityList
    }
    w.WriteHeader(http.StatusOK)
    if len(cityList) == 0 {
        w.Write([]byte(`{"cities": []}`))
        return
    }
    json.NewEncoder(w).Encode(cityList)

}

func init() {
    rand.Seed(time.Now().UnixNano()) // Creates a new seed for randomising the access token
}

func genString(n int) string { // Generates a randomised string from the character runes
    b := make([]rune, n)
    for i := range b {
        b[i] = characterRunes[rand.Intn(len(characterRunes))]
    }
    return string(b)
}

func generateToken(n ...int) string { // Generates a token for when a new user registers their details
    characters := 32

    if len(n) > 0 {
        characters = n[0]
    }

    randString := genString(characters)

    h := sha256.New()
    h.Write([]byte(randString))
    generatedToken := h.Sum(nil)

    return fmt.Sprintf("%x", generatedToken)

}

func APIAuth(endpoint func(http.ResponseWriter, *http.Request)) http.Handler { // Middleware to check if access token is contained within header when running searchCity
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

        accessToken := r.Header.Get("x-api-key")

        // Checks token in db
        usersCollection := client.Database(os.Getenv("CITY_DB")).Collection(os.Getenv("COL_USER"))
        filter := bson.D{
            primitive.E{
                Key: "accesstoken", Value: accessToken,
            },
        }

        var user User
        err := usersCollection.FindOne(context.TODO(), filter).Decode(&user)
        if err != nil {
            http.Error(w, `Unauthorized access`, http.StatusUnauthorized)
        } else if len(accessToken) == 0 {
            http.Error(w, `Unauthorized access`, http.StatusUnauthorized)
        } else {
            endpoint(w, r)
        }
    })
}

func UserAuth(endpoint func(http.ResponseWriter, *http.Request)) http.Handler { // Middleware to check if user registering has appropriate auth token
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        accessToken := r.Header.Get("x-access-token")
        if len(accessToken) == 0 {
            http.Error(w, "Unauthorized access, no token", http.StatusUnauthorized)
            return
        }

        if accessToken != os.Getenv("USER_AUTH_TOKEN") {
            http.Error(w, "Unauthorized access", http.StatusUnauthorized)
            return
        }

        endpoint(w, r)
    })
}

netstat -tulpn with containers running

Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      -                   
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      -                   
tcp        0      0 127.0.0.1:5432          0.0.0.0:*               LISTEN      -                   
tcp        0      0 192.168.0.101:40571     0.0.0.0:*               LISTEN      3086/rygel          
tcp        0      0 127.0.0.1:5054          0.0.0.0:*               LISTEN      2967/python3        
tcp        0      0 172.17.0.1:41599        0.0.0.0:*               LISTEN      3086/rygel          
tcp        0      0 127.0.0.1:46624         0.0.0.0:*               LISTEN      2358/kited          
tcp        0      0 0.0.0.0:8001            0.0.0.0:*               LISTEN      -                   
tcp        0      0 127.0.0.1:34179         0.0.0.0:*               LISTEN      3086/rygel          
tcp        0      0 172.23.0.1:39273        0.0.0.0:*               LISTEN      3086/rygel          
tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN      -                   
tcp        0      0 0.0.0.0:54321           0.0.0.0:*               LISTEN      -                   
tcp6       0      0 ::1:631                 :::*                    LISTEN      -                   
tcp6       0      0 :::8001                 :::*                    LISTEN      -                   
tcp6       0      0 :::5900                 :::*                    LISTEN      3083/gnome-remote-d 
tcp6       0      0 :::54321                :::*                    LISTEN      -                   
udp        0      0 127.0.0.53:53           0.0.0.0:*                           -                   
udp        0      0 172.17.0.1:41320        0.0.0.0:*                           3086/rygel          
udp        0      0 0.0.0.0:631             0.0.0.0:*                           -                   
udp        0      0 0.0.0.0:50334           0.0.0.0:*                           -                   
udp        0      0 239.255.255.250:1900    0.0.0.0:*                           3086/rygel          
udp        0      0 172.17.0.1:1900         0.0.0.0:*                           3086/rygel          
udp        0      0 239.255.255.250:1900    0.0.0.0:*                           3086/rygel          
udp        0      0 172.23.0.1:1900         0.0.0.0:*                           3086/rygel          
udp        0      0 239.255.255.250:1900    0.0.0.0:*                           3086/rygel          
udp        0      0 192.168.0.101:1900      0.0.0.0:*                           3086/rygel          
udp        0      0 239.255.255.250:1900    0.0.0.0:*                           3086/rygel          
udp        0      0 127.0.0.1:1900          0.0.0.0:*                           3086/rygel          
udp        0      0 127.0.0.1:52502         0.0.0.0:*                           3086/rygel          
udp        0      0 172.23.0.1:45184        0.0.0.0:*                           3086/rygel          
udp        0      0 192.168.0.101:53552     0.0.0.0:*                           3086/rygel          
udp        0      0 0.0.0.0:5353            0.0.0.0:*                           -                   
udp6       0      0 :::42415                :::*                                -                   
udp6       0      0 :::5353                 :::*                                -                   

CodePudding user response:

Please, change the following line in the .env file:

DB_URI=mongodb://mongo-test:8001

to

DB_URI=mongodb://mongo-test:27017

The containers run in the same container network when you start them with the docker compose up command. That means you need to specify the container port instead of the host port. The container port always goes second in the Docker kingdom: <host port>:<container port>.

  •  Tags:  
  • Related