Skip to content

Instantly share code, notes, and snippets.

@samdroid-apps
Created August 9, 2014 07:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samdroid-apps/8d527279594e8f35492b to your computer and use it in GitHub Desktop.
Save samdroid-apps/8d527279594e8f35492b to your computer and use it in GitHub Desktop.
Social Help Router

Usage

GET /missing/ID

Log that ID as missing an being requested, redirect to forum.

GET /records

Get a json map in the format of bundle ID to number of times requested

PATCH /records

Save the current json map to the disk (useful before server restarts)

package main
import (
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/missing/:ID", func(c *gin.Context) {
id := c.Params.ByName("ID")
RecordMissingBundle(id)
c.Writer.Header().Set(
"Location", "http://54.187.40.150/t/category-not-found/")
c.String(301, "http://54.187.40.150/t/category-not-found/")
})
r.GET("/records", func(c *gin.Context) {
c.JSON(200, GetRecords())
})
r.PATCH("/records", func(c *gin.Context) {
err := SaveRecords()
if err != nil {
c.String(500,
"Internal server error\n\n\tCould not save (see log)")
} else {
c.String(200, "Saved!")
}
})
LoadRecords()
r.Run(":5051")
}
package main
import (
"os"
"io/ioutil"
"sync/atomic"
"encoding/json"
)
const (
RECORDS_FILE string = "records.json"
)
type Records map[string]*int64
var (
records Records
)
func RecordMissingBundle(id string) {
if _, ok := records[id]; !ok {
x := int64(0)
records[id] = &x
}
atomic.AddInt64(records[id], 1)
}
func GetRecords() Records {
r := Records{}
for k, v := range records {
n := atomic.LoadInt64(v)
r[k] = &n
}
return r
}
func SaveRecords() error {
data, err := json.Marshal(GetRecords())
if err != nil {
return err
}
return ioutil.WriteFile(RECORDS_FILE, data, 0644)
}
func LoadRecords() {
records = Records{}
if _, err := os.Stat(RECORDS_FILE); os.IsNotExist(err) {
// No records file
return
}
data, err := ioutil.ReadFile(RECORDS_FILE)
if err != nil {
panic(err)
}
tmp := map[string]int64{}
err = json.Unmarshal(data, &tmp)
if err != nil {
panic(err)
}
for k, v := range tmp {
v := v
records[k] = &v
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment