Skip to content

Commit

Permalink
first
Browse files Browse the repository at this point in the history
  • Loading branch information
jpthor committed Jun 28, 2019
0 parents commit 789bac8
Show file tree
Hide file tree
Showing 11 changed files with 444 additions and 0 deletions.
20 changes: 20 additions & 0 deletions .fsw.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
desc: cloudsql-mysql
triggers:
- name: ""
pattens:
- '**/*.go'
- '**/*.html'
env:
FIREBASE_SERVICE_FILE: "./firebase.json"
GCP_PROJECT_ID: "staging-can-work"
PORT: 5000
DEFAULT_HOST: "https://staging-can-work.firebaseapp.com/"
cmd: clear; go build && ./open-graph
shell: true
delay: 100ms
stop_timeout: 500ms
signal: KILL
kill_signal: ""
watch_paths:
- .
watch_depth: 0
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
open-graph
.DS_Store
61 changes: 61 additions & 0 deletions .gitlab-ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
image: registry.gitlab.com/canyacoin/canyacore/devops/gcloud-golang-111:1.0

stages:
- deploy

variables:
GOPATH: /go
APP_PATH: $GOPATH/src/gitlab.com/$CI_PROJECT_PATH

before_script:
- echo "+ perfoming build on alpine '`cat /etc/alpine-release`' with '`go version`'"
- echo "+ relocating cloned sources to $APP_PATH to satisfy go's package tree structure"
- mkdir -p `dirname $APP_PATH`
- mv /builds/$CI_PROJECT_PATH $APP_PATH
- mkdir -p /builds/$CI_PROJECT_PATH
- export GOPATH=$GOPATH

deploy:staging:
stage: deploy
environment:
name: staging
script:
- cd $APP_PATH
- echo "Deploy to staging target GAE instance with project ID $GCP_PROJECT_ID"
- echo $GCP_KEY > /tmp/$CI_PIPELINE_ID.json
- echo -n "+ using GCP KEY for staging deployer " && cat /tmp/$CI_PIPELINE_ID.json
- echo $FIREBASE_KEY > ./firebase.json
- echo $DISPATCH_YAML_STAGING | base64 -d > ./dispatch.yaml
- go get
- go get github.com/stretchr/testify/assert
- go test -v
- gcloud auth activate-service-account --key-file /tmp/$CI_PIPELINE_ID.json
- gcloud config set project $GCP_PROJECT_ID
- gcloud --quiet app deploy dispatch.yaml
- gcloud --quiet app deploy app.staging.yaml
- curl --fail https://open-graph-dot-$GCP_PROJECT_ID.appspot.com/status
only:
- master
allow_failure: false

deploy:production:
stage: deploy
environment:
name: production
script:
- cd $APP_PATH
- echo "Deploy to production target GAE instance with project ID $GCP_PROJECT_ID"
- echo $GCP_KEY > /tmp/$CI_PIPELINE_ID.json
- echo -n "+ using GCP KEY for production deployer " && cat /tmp/$CI_PIPELINE_ID.json
- echo $FIREBASE_KEY > ./firebase.json
- echo $DISPATCH_YAML | base64 -d > ./dispatch.yaml
- go get
- gcloud auth activate-service-account --key-file /tmp/$CI_PIPELINE_ID.json
- gcloud config set project $GCP_PROJECT_ID
- gcloud --quiet app deploy dispatch.yaml
- gcloud --quiet app deploy app.production.yaml
- curl --fail https://open-graph-dot-$GCP_PROJECT_ID.appspot.com/status
only:
- master
when: manual
allow_failure: false
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
****

> **Mirror**
> This repo mirrors from Gitlab to Github. Please commit to the Gitlab repo:
> https://gitlab.com/canyacoin/canwork/services/open-graph
****

# open-graph

Generate HTML server side rendered containing open graph meta tags for CANWork Jobs & Profiles

Deletes branches
13 changes: 13 additions & 0 deletions app.production.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
runtime: go111

service: open-graph

env_variables:
GIN_MODE: release
FIREBASE_SERVICE_FILE: ./firebase.json
GCP_PROJECT_ID: canwork-io
DEFAULT_HOST: https://www.canwork.io/

handlers:
- url: /.*
script: auto
13 changes: 13 additions & 0 deletions app.staging.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
runtime: go111

service: open-graph

env_variables:
GIN_MODE: release
FIREBASE_SERVICE_FILE: ./firebase.json
GCP_PROJECT_ID: staging-can-work
DEFAULT_HOST: https://staging-can-work.firebaseapp.com/

handlers:
- url: /.*
script: auto
38 changes: 38 additions & 0 deletions functions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package main

import (
"context"
"fmt"
"os"

"google.golang.org/api/iterator"
)

func mustGetenv(k string) string {
v := os.Getenv(k)
if v == "" {
panic(fmt.Sprintf("%s environment variable not set.", k))
}
return v
}

func getSlugSnap(ctx context.Context, collection string, slug string) map[string]interface{} {
var (
collectionref = firestoreClient.Collection(collection)
iter = collectionref.Where("slug", "==", slug).Documents(ctx)
result map[string]interface{}
)

defer iter.Stop()
for {
doc, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
logger.Errorf("unable to retrieve document for slug: %s error was: %s", slug, err.Error())
}
result = doc.Data()
}
return result
}
118 changes: 118 additions & 0 deletions handlers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
package main

import (
"context"
"fmt"
"net/http"
"strings"

humanize "github.com/dustin/go-humanize"
"github.com/gin-gonic/gin"
"github.com/mitchellh/mapstructure"
"gitlab.com/canya-com/shared/data-structures/canwork"
)

var (
host = mustGetenv("DEFAULT_HOST")
projectID = mustGetenv("GCP_PROJECT_ID")
)

func jobHandler(c *gin.Context) {
var (
ctx = context.Background()
slug = c.Param("slug")
ua = c.Request.Header.Get("User-Agent")
job canwork.JobDocument
user canwork.UserDocument
// default value
ogTitle = "Hire professional freelancers from around the globe to complete your project or job"
ogDescription = "CanWork is a global platform used to hire affordable, quality freelancers from around the globe to do the work you need on demand. It allows on demand remote project management with multiple flexible payments options including crypto payments"
ogImage = fmt.Sprintf("%sassets/img/CanYa_OpenGraph_CanWork.png", host)
// url
isFromFb = strings.HasPrefix(ua, "facebookexternalhit")
ogURL = host
redirectURL = host
)

jobdata := getSlugSnap(ctx, "public-jobs", slug)
mapstructure.Decode(jobdata, &job)

if job.Slug != "" {
uid := job.ClientID
userref := firestoreClient.Doc(fmt.Sprintf("users/%s", uid))
usersnap, err := userref.Get(ctx)
if err != nil {
logger.Errorf("unable to retrieve user document for ID: %s error was: %s", uid, err.Error())
}
mapstructure.Decode(usersnap.Data(), &user)
}

if job.Information.Title != "" {
ogTitle = job.Information.Title
ogDescription = job.Information.Description
ogImage = user.Avatar.URI
ogURL = fmt.Sprintf("%sjobs/public/%s", host, slug)
redirectURL = ogURL
if isFromFb {
ogURL = fmt.Sprintf("https://open-graph-dot-%s.appspot.com/job/%s", projectID, slug)
}
}

c.HTML(http.StatusOK, "meta.html",
gin.H{
"ogTitle": ogTitle,
"ogType": "article",
"ogDescription": ogDescription,
"ogImage": ogImage,
"ogURL": ogURL,
"redirectURL": redirectURL,
})
}

func profileHandler(c *gin.Context) {
var (
ctx = context.Background()
slug = c.Param("slug")
ua = c.Request.Header.Get("User-Agent")
user canwork.UserDocument
// default value
ogTitle = "Hire professional freelancers from around the globe to complete your project or job"
ogDescription = "CanWork is a global platform used to hire affordable, quality freelancers from around the globe to do the work you need on demand. It allows on demand remote project management with multiple flexible payments options including crypto payments"
ogImage = fmt.Sprintf("%sassets/img/CanYa_OpenGraph_CanYa.png", host)
// url
isFromFb = strings.HasPrefix(ua, "facebookexternalhit")
ogURL = host
redirectURL = host
)

userdata := getSlugSnap(ctx, "users", slug)
mapstructure.Decode(userdata, &user)

if user.Name != "" {
ogTitle = user.Name
ogDescription = user.Bio
ogImage = user.Avatar.URI
ogURL = fmt.Sprintf("%sprofile/%s", host, slug)
redirectURL = ogURL
if isFromFb {
ogURL = fmt.Sprintf("https://open-graph-dot-%s.appspot.com/profile/%s", projectID, slug)
}
}
c.HTML(http.StatusOK, "meta.html",
gin.H{
"ogTitle": ogTitle,
"ogType": "profile",
"ogDescription": ogDescription,
"ogImage": ogImage,
"ogURL": ogURL,
"redirectURL": redirectURL,
})
}

func statusHandler(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"status": "OK",
"serviceID": serviceID,
"serviceStarted": humanize.Time(startedAt),
})
}
64 changes: 64 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package main

import (
"context"
"os"
"time"

"cloud.google.com/go/firestore"
gintemplate "github.com/foolin/gin-template"
"github.com/gin-gonic/gin"
"google.golang.org/api/option"

logging "github.com/op/go-logging"
)

var (
serviceID = "open-graph"
router *gin.Engine
logger = logging.MustGetLogger("main")
startedAt = time.Now()
firestoreClient *firestore.Client
)

func init() {
var err error
logFormatter := logging.MustStringFormatter(`%{color}%{time:15:04:05.000} %{shortfunc} ▶ %{level:.10s} %{id:03x}%{color:reset} %{message}`)
logging.SetFormatter(logFormatter)
consoleBackend := logging.NewLogBackend(os.Stdout, "", 0)
consoleBackend.Color = true
logging.SetLevel(logging.DEBUG, "main")

// connect firestore
firebaseServiceFile := mustGetenv("FIREBASE_SERVICE_FILE")
gcpProjectID := mustGetenv("GCP_PROJECT_ID")

firestoreClient, err = firestore.NewClient(
context.Background(),
gcpProjectID,
option.WithServiceAccountFile(firebaseServiceFile))
if err != nil {
logger.Fatalf("unable to connect to firestore. error was: %s", err.Error())
}

<<<<<<< HEAD
router = gin.Default()
router.Use(gin.Logger())
router.HTMLRender = gintemplate.Default()
=======
}

func setupRouter() *gin.Engine {
r := gin.New()
r.Use(gin.Logger())
r.HTMLRender = gintemplate.Default()
>>>>>>> go-testing

router.GET("/job/:slug", jobHandler)
router.GET("/profile/:slug", profileHandler)
router.GET("/status/", statusHandler)
}

func main() {
router.Run()
}
Loading

0 comments on commit 789bac8

Please sign in to comment.