Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
imoonkin committed Dec 20, 2023
1 parent 567395c commit 24a2483
Show file tree
Hide file tree
Showing 10 changed files with 263 additions and 23 deletions.
33 changes: 33 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# This workflow will build a golang project
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-go

name: Release

on:
push:
tags:
- "v*.*.*"

jobs:

build:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v3

- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: '1.21'

- name: Build
run: go build -o ./main ./...
- run: mkdir sharedNoteServer; mv main sharedNoteServer/sharedNoteServer; mv run.sh sharedNoteServer/; mv sharedNoteServer.yaml sharedNoteServer/; mv sharednote-cert-issuer.yaml sharedNoteServer/
- name: Tar
run: tar czf sharedNoteServer.tar.gz sharedNoteServer
- name: Release
uses: softprops/action-gh-release@v1
with:
files: sharedNoteServer.tar.gz
13 changes: 11 additions & 2 deletions addNote.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,25 @@ import (
)

var addNoteHandler = func(resp http.ResponseWriter, req *http.Request) {
if forward(resp, req) {
return
}
var n note
if err := json.NewDecoder(req.Body).Decode(&n); err != nil || len(n.title) == 0 || len(n.address) == 0 {
if err := json.NewDecoder(req.Body).Decode(&n); err != nil || len(n.Title) == 0 || len(n.Address) == 0 {
resp.WriteHeader(http.StatusForbidden)
resp.Write([]byte("不太对"))
log.Fatalf("err=%+v , title=%+v, addr=%+v", err, n.Title, n.Address)
return
}

// todo valid range check
// todo update DB
// todo update DB ^^^
n.Latitude = float64(int64(n.Latitude*1000000)) / 1000000
n.Longitude = float64(int64(n.Longitude*1000000)) / 1000000
if err := addNote(n); err != nil {
resp.WriteHeader(http.StatusInternalServerError)
log.Fatalln(err)
}
resp.WriteHeader(http.StatusOK)

}
34 changes: 20 additions & 14 deletions db.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,31 @@ import (
"database/sql"
"github.com/go-sql-driver/mysql"
"log"
"time"
)

type note struct {
latitude float32
longitude float32
title string
address string
content string
Id int64 `json:"id"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
Title string `json:"title"`
Address string `json:"address"`
Content string `json:"content"`
UpdateTime int64 `json:"updateTime"`
Visible bool `json:"visible"`

UpdateTimeFormatted string `json:"updateTimeFormatted"`
}

var db *sql.DB

func initDB() {
cfg := mysql.Config{
User: "owen",
Passwd: "123haha123",
User: "imoonkin",
Passwd: "passwd",
Net: "tcp",
Addr: "127.0.0.1:3306",
DBName: "sharedNotes",
Addr: "hostmysql:3306",
DBName: "sharednotedb",
}
var err error
if db, err = sql.Open("mysql", cfg.FormatDSN()); err != nil {
Expand All @@ -37,22 +43,22 @@ func initDB() {

func addNote(n note) error {
if _, err := db.Exec(
"insert into sharednote (latitude,longitude,title,address,content) values (?,?,?,?,?)",
n.latitude, n.longitude, n.title, n.address, n.content); err != nil {
"insert into sharedNote (latitude,longitude,title,address,content,updateTime,visible) values (?,?,?,?,?,?,?)",
n.Latitude, n.Longitude, n.Title, n.Address, n.Content, time.Now().Unix(), true); err != nil {
return err
}
return nil
}
func rangeFetch(lat1, lng1, lat2, lng2 float32) ([]note, error) {
func rangeFetch(lat1, lng1, lat2, lng2 float64) ([]note, error) {
ret := []note{}
rows, err := db.Query("select * from sharednote where latitude between lat1 and lat2 and longitude between lng1 and lng2 limit 100")
rows, err := db.Query("select id,latitude,longitude,title,address,content,updateTime,visible from sharedNote where latitude between ? and ? and longitude between ? and ? limit 100", lat1, lat2, lng1, lng2)
if err != nil {
return ret, err
}
defer rows.Close()
for rows.Next() {
var n note
if err = rows.Scan(&n.latitude, &n.longitude, &n.title, &n.address, &n.content); err != nil {
if err = rows.Scan(&n.Id, &n.Latitude, &n.Longitude, &n.Title, &n.Address, &n.Content, &n.UpdateTime, &n.Visible); err != nil {
return ret, err
}
ret = append(ret, n)
Expand Down
14 changes: 14 additions & 0 deletions fileHandler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package main

import (
"net/http"
)

var fileHandler = func(resp http.ResponseWriter, req *http.Request) {
if len(req.Header.Get("X-ENV-WEB")) > 0 && len(req.Header.Get("X-Redirect")) == 0 {
env := req.Header.Get("X-ENV-WEB")
http.FileServer(http.Dir("/root/static/sharedNoteWeb"+env)).ServeHTTP(resp, req)
return
}
http.FileServer(http.Dir(`/root/static/sharedNoteWeb`)).ServeHTTP(resp, req)
}
56 changes: 56 additions & 0 deletions forward.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package main

import (
"io"
"log"
"net/http"
)

var svc = "shared-note-server"

func forward(resp http.ResponseWriter, req *http.Request) (needForward bool) {
if !(len(req.Header.Get("X-ENV")) > 0 && len(req.Header.Get("X-Redirect")) == 0) {
return false
}
needForward = true
env := req.Header.Get("X-ENV")
url := req.URL
log.Printf("copied url=%+v , %+v, %+v, %+v, %+v, %+v", url, url.Scheme, url.Host, url.Opaque, url.User, url.OmitHost)
url.Scheme = "http"
url.Host = svc + env

proxyReq, err := http.NewRequest(req.Method, url.String(), req.Body)
if err != nil {
log.Printf("wtf err1=%+v", err)
}

proxyReq.Header.Set("Host", svc+env)
proxyReq.Header.Set("X-Redirect", "1")
proxyReq.Header.Set("X-Forwarded-For", req.RemoteAddr)

for header, values := range req.Header {
for _, value := range values {
proxyReq.Header.Add(header, value)
}
}

client := &http.Client{}
proxyRes, err := client.Do(proxyReq)
if err != nil {
resp.WriteHeader(http.StatusOK)
resp.Write([]byte(err.Error()))
log.Printf("wtf err2=%+v", err)
return
}
resp.WriteHeader(proxyRes.StatusCode)
proxyBody, err := io.ReadAll(proxyRes.Body)
if err != nil {
resp.WriteHeader(http.StatusOK)
resp.Write([]byte(err.Error()))
log.Printf("wtf err3=%+v", err)
return
}

resp.Write(proxyBody)
return
}
35 changes: 31 additions & 4 deletions range.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"strconv"
)

func parseLatlon(param url.Values, s string) (float32, bool) {
func parseLatlon(param url.Values, s string) (float64, bool) {
if len(param[s]) != 1 {
return 0, false
}
Expand All @@ -20,23 +20,34 @@ func parseLatlon(param url.Values, s string) (float32, bool) {
if math.IsNaN(ll) || math.IsInf(ll, 0) || ll < (-370) || 370 < ll {
return 0, false
}
return float32(ll), true
return ll, true
}

type MapPoint struct {
Id int64 `json:"id"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
NotesInfo []note `json:"notesInfo"`
}

var rangeHandler = func(resp http.ResponseWriter, req *http.Request) {
if forward(resp, req) {
return
}
param := req.URL.Query()
lat1, ok1 := parseLatlon(param, "latitude1")
lat2, ok2 := parseLatlon(param, "latitude2")
lng1, ok3 := parseLatlon(param, "longitude1")
lng2, ok4 := parseLatlon(param, "longitude2")
if !(ok1 && ok2 && ok3 && ok4) {
resp.WriteHeader(http.StatusForbidden)
log.Fatalf("param error \n")
}
if lat1 > 91 || lat1 < (-91) || lat2 > 91 || lat2 < (-91) ||
lng1 > 181 || lng2 > 181 || lng1 < (-181) || lng2 < (-181) {
resp.WriteHeader(http.StatusOK)
if _, err := resp.Write([]byte("hey yo motherfucker")); err != nil {
log.Fatalf("taunt failed %+v", err)
log.Fatalf("taunt failed %+v \n", err)
}
return
}
Expand All @@ -46,7 +57,23 @@ var rangeHandler = func(resp http.ResponseWriter, req *http.Request) {
resp.WriteHeader(http.StatusInternalServerError)
log.Fatalf("range query db error %+v \n", err)
}
notesString, err := json.Marshal(notes)
var ret []MapPoint
var lastLat, lastLng float64 = 1000, 1000
for _, n := range notes {
if math.Abs(lastLat-n.Latitude) < 0.00001 && math.Abs(lastLng-n.Longitude) < 0.00001 {
ret[len(ret)-1].NotesInfo = append(ret[len(ret)-1].NotesInfo, n)
} else {
ret = append(ret, MapPoint{
Id: n.Id,
Latitude: n.Latitude,
Longitude: n.Longitude,
NotesInfo: []note{n},
})
}
lastLat = n.Latitude
lastLng = n.Longitude
}
notesString, err := json.Marshal(ret)
if err != nil {
resp.WriteHeader(http.StatusInternalServerError)
log.Fatalf("range query marshal error %+v \n", err)
Expand Down
4 changes: 4 additions & 0 deletions run.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/bin/sh
chmod 777 $(dirname -- "$0")/sharedNoteServer
cd $(dirname -- "$0")
./sharedNoteServer
5 changes: 2 additions & 3 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,8 @@ func main() {
log.SetOutput(f)
defer f.Close()

//initDB()

http.Handle("/", http.FileServer(http.Dir("C:\\SoftWare\\WebProjects\\sharednotes\\dist"))) // todo use nginx
initDB()
http.HandleFunc("/", fileHandler)
http.HandleFunc("/range", rangeHandler)
http.HandleFunc("/add", addNoteHandler)

Expand Down
69 changes: 69 additions & 0 deletions sharedNoteServer.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: shared-note-ingress
annotations:
cert-manager.io/issuer: sharednote-issuer
spec:
ingressClassName: "traefik"
tls:
- secretName: sharednote-cert
hosts:
- note.imoonkin.online
rules:
- http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: shared-note-server
port:
number: 12808
---
apiVersion: v1
kind: Service
metadata:
name: shared-note-server
spec:
ports:
- port: 12808
protocol: TCP
selector:
app: shared-note-server
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: shared-note-server
spec:
selector:
matchLabels:
app: shared-note-server
strategy:
type: Recreate
template:
metadata:
labels:
app: shared-note-server
spec:
containers:
- image: imoonkin/goproductpod:latest
name: shared-note-server
ports:
- containerPort: 12808
name: sharednote-p
volumeMounts:
- name: binaries
mountPath: /root/server
- name: static
mountPath: /root/static
volumes:
- name: binaries
hostPath:
path: /home/product/sharedNoteServer
type: DirectoryOrCreate
- name: static
hostPath:
path: /home/product/static
type: DirectoryOrCreate
23 changes: 23 additions & 0 deletions sharednote-cert-issuer.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
apiVersion: cert-manager.io/v1
kind: Issuer
metadata:
name: sharednote-issuer
spec:
acme:
server: https://acme-v02.api.letsencrypt.org/directory
email: [email protected]
privateKeySecretRef:
name: acme-account-key
solvers:
- http01:
ingress:
ingressClassName: traefik
---
apiVersion: v1
kind: Secret
metadata:
name: sharednote-cert
type: kubernetes.io/tls
stringData:
tls.key: ""
tls.crt: ""

0 comments on commit 24a2483

Please sign in to comment.