text stringlengths 11 4.05M |
|---|
/*
Copyright 2021 The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package addon
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestLocalReader(t *testing.T) {
r := localReader{name: "local", dir: "./testdata/local"}
m, err := r.ListAddonMeta()
assert.NoError(t, err)
assert.Equal(t, len(m["local"].Items), 2)
file, err := r.ReadFile("metadata.yaml")
assert.NoError(t, err)
assert.Equal(t, file, metaFile)
file, err = r.ReadFile("resources/parameter.cue")
assert.NoError(t, err)
assert.Equal(t, true, strings.Contains(file, parameterFile))
}
const (
metaFile = `name: test-local-addon
version: 1.0.0
description: This is a addon for test when install addon from local
icon: https://www.terraform.io/assets/images/logo-text-8c3ba8a6.svg
url: https://terraform.io/
tags: []
deployTo:
control_plane: true
runtime_cluster: false
dependencies: []
invisible: false`
parameterFile = `parameter: {
// test wrong parameter
example: *"default"
}`
)
|
package output
import (
"fmt"
"github.com/fatih/color"
)
func Info(s string) {
green := color.New(color.FgGreen, color.Bold)
green.Printf("[%-12s] ", "Information")
fmt.Print(s)
}
func Error(s string) {
red := color.New(color.FgRed, color.Bold)
red.Printf("[%-12s] ", "Error")
fmt.Print(s)
}
func Installer(s string) {
green := color.New(color.FgGreen, color.Bold)
green.Printf("[%-12s] ", "Installer")
fmt.Print(s)
}
func Custom(level string, s string) {
green := color.New(color.FgGreen, color.Bold)
green.Printf("[%-12s] ", level)
fmt.Print(s)
} |
package handler
import (
"fmt"
"html/template"
"io"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/GoGroup/Movie-and-events/event"
"github.com/GoGroup/Movie-and-events/form"
"github.com/GoGroup/Movie-and-events/hash"
"github.com/GoGroup/Movie-and-events/rtoken"
"github.com/GoGroup/Movie-and-events/cinema"
"github.com/GoGroup/Movie-and-events/controller"
"github.com/GoGroup/Movie-and-events/hall"
"github.com/GoGroup/Movie-and-events/model"
"github.com/GoGroup/Movie-and-events/movie"
"github.com/GoGroup/Movie-and-events/schedule"
)
type AdminHandler struct {
tmpl *template.Template
csrv cinema.CinemaService
hsrv hall.HallService
ssrv schedule.ScheduleService
msrv movie.MovieService
evrv event.EventService
csrfSignKey []byte
}
const nameKey = "name"
const locationKey = "location"
const descriptionKey = "description"
const datetimekey = "datetime"
const fileKey = "file"
const capKey = "cap"
const priceKey = "price"
const vipcapkey = "vipcap"
const vipKey = "vip"
const csrfHKey = "_csrf"
func NewAdminHandler(t *template.Template, cs cinema.CinemaService, hs hall.HallService, ss schedule.ScheduleService, ms movie.MovieService, ev event.EventService, csKey []byte) *AdminHandler {
return &AdminHandler{tmpl: t, csrv: cs, hsrv: hs, ssrv: ss, msrv: ms, evrv: ev, csrfSignKey: csKey}
}
func (m *AdminHandler) AdminCinema(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
if m.isParsableFormPost(w, r) {
fmt.Println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
cinemaNewForm := form.Input{Values: r.PostForm, VErrors: form.ValidationErrors{}, CSRF: r.FormValue(csrfHKey)}
cinemaNewForm.ValidateRequiredFields("cinemaName")
fmt.Println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
var NewCinemaArray []model.Cinema
x, _ := m.csrv.Cinemas()
for _, element := range x {
element.Halls, _ = m.hsrv.CinemaHalls(element.ID)
NewCinemaArray = append(NewCinemaArray, element)
}
tempo1 := struct {
Cinemas []model.Cinema
From form.Input
}{Cinemas: NewCinemaArray, From: cinemaNewForm}
if !cinemaNewForm.IsValid() {
fmt.Println(m.tmpl.ExecuteTemplate(w, "adminCinemaList.layout", tempo1))
return
}
c := model.Cinema{
CinemaName: r.FormValue("cinemaName"),
}
cc, ee := m.csrv.StoreCinema(&c)
fmt.Println(cc)
fmt.Println(ee)
fmt.Println(m.tmpl.ExecuteTemplate(w, "adminCinemaList.layout", tempo1))
}
} else if r.Method == http.MethodGet {
var errr []error
var NewCinemaArray []model.Cinema
c, err := m.csrv.Cinemas()
for _, element := range c {
element.Halls, errr = m.hsrv.CinemaHalls(element.ID)
NewCinemaArray = append(NewCinemaArray, element)
}
fmt.Println(NewCinemaArray)
if len(err) > 0 || len(errr) > 0 {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
CSFRToken, _ := rtoken.GenerateCSRFToken(m.csrfSignKey)
tempo1 := struct {
Cinemas []model.Cinema
From form.Input
}{Cinemas: NewCinemaArray, From: form.Input{CSRF: CSFRToken}}
fmt.Println(m.tmpl.ExecuteTemplate(w, "adminCinemaList.layout", tempo1))
}
}
func (m *AdminHandler) AdminScheduleDelete(w http.ResponseWriter, r *http.Request) {
var HallID int
var SchedulelID int
p := strings.Split(r.URL.Path, "/")
if len(p) == 1 {
fmt.Println("in first if")
//return defaultCode, p[0]
} else if len(p) > 1 {
fmt.Println("..in first if")
code, err := strconv.Atoi(p[5])
code2, err2 := strconv.Atoi(p[6])
fmt.Println(err)
fmt.Println(p)
fmt.Println(code)
if err == nil && err2 == nil {
fmt.Println(".....in first if")
HallID = code
SchedulelID = code2
}
}
fmt.Println("In admin schedule*****************")
fmt.Println("trying to delete*****************")
uSchID := uint(SchedulelID)
fmt.Println("trying to delete2*****************")
fmt.Println(m)
fmt.Println(m.ssrv)
fmt.Println(uSchID)
d, errrr := m.ssrv.DeleteSchedules(uSchID)
fmt.Println(d, "***********deltegel***********")
fmt.Println(errrr, "***********errrr***********")
fmt.Println(r.FormValue("hId"))
var All [][]model.ScheduleWithMovie
var SWM []model.ScheduleWithMovie
var err []error
var sm model.ScheduleWithMovie
var schedules []model.Schedule
uHallID := uint(HallID)
Days := []string{"Monday", "Tuesday", "Wednsday", "Thursday", "Friday", "Saturday", "Sunday"}
for _, d := range Days {
schedules, err = m.ssrv.ScheduleHallDay(uHallID, d)
SWM = nil
for _, s := range schedules {
m, _, _ := controller.GetMovieDetails(s.MoviemID)
sm = model.ScheduleWithMovie{s, m.Title}
SWM = append(SWM, sm)
}
All = append(All, SWM)
}
hall, _ := m.hsrv.Hall(uint(HallID))
fmt.Println(hall, "******my hall******")
cinema, _ := m.csrv.Cinema(uint(hall.CinemaID))
fmt.Println(cinema, "******my cinema******")
tempo := struct {
HallId int
List [][]model.ScheduleWithMovie
Hall *model.Hall
Cinema *model.Cinema
}{
HallId: HallID,
List: All,
Hall: hall,
Cinema: cinema,
}
if len(err) > 0 {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
fmt.Println(tempo)
fmt.Println(m.tmpl.ExecuteTemplate(w, "adminScheduleList.layout", tempo))
}
func (m *AdminHandler) AdminDeleteEvents(w http.ResponseWriter, r *http.Request) {
var EID uint
p := strings.Split(r.URL.Path, "/")
if len(p) == 1 {
fmt.Println("in first if")
//return defaultCode, p[0]
} else if len(p) > 1 {
fmt.Println("..in first if")
code2, err2 := strconv.Atoi(p[4])
fmt.Println(err2)
fmt.Println(p)
if err2 == nil {
fmt.Println(".....in first if")
EID = uint(code2)
}
}
h, e := m.evrv.DeleteEvent(EID)
if len(e) > 0 {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
fmt.Println("delteed", h)
fmt.Println("%%%%%%%%%%%%%%%%%")
events, errr := m.evrv.Events()
fmt.Println(errr)
if len(errr) > 0 {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
CSFRToken, _ := rtoken.GenerateCSRFToken(m.csrfSignKey)
tempo := struct {
Events []model.Event
From form.Input
ID uint
}{Events: events, From: form.Input{CSRF: CSFRToken}, ID: EID}
fmt.Println("works")
fmt.Println(m.tmpl.ExecuteTemplate(w, "adminEventList.layout", tempo))
fmt.Println("where")
}
func (m *AdminHandler) AdminDeleteHalls(w http.ResponseWriter, r *http.Request) {
var CID uint
var HID uint
p := strings.Split(r.URL.Path, "/")
if len(p) == 1 {
fmt.Println("in first if")
//return defaultCode, p[0]
} else if len(p) > 1 {
fmt.Println("..in first if")
code, err := strconv.Atoi(p[5])
code2, err2 := strconv.Atoi(p[6])
fmt.Println(err)
fmt.Println(err2)
fmt.Println(p)
fmt.Println(code)
if err == nil {
fmt.Println(".....in first if")
CID = uint(code)
HID = uint(code2)
}
}
h, e := m.hsrv.DeleteHall(HID)
if len(e) > 0 {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
fmt.Println("delteed", h)
fmt.Println("%%%%%%%%%%%%%%%%%")
halls, errr := m.hsrv.CinemaHalls(CID)
if len(errr) > 0 {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
tempo := struct {
Halls []model.Hall
Cid uint
}{Halls: halls, Cid: CID}
fmt.Println(m.tmpl.ExecuteTemplate(w, "halls.layout", tempo))
}
func (m *AdminHandler) AdminEventsNew(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(0)
CSFRToken, err := rtoken.GenerateCSRFToken(m.csrfSignKey)
if r.Method == http.MethodGet {
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
fmt.Println(m.tmpl.ExecuteTemplate(w, "adminNewEvent.layout", form.Input{
CSRF: CSFRToken}))
return
}
if m.isParsableFormPost(w, r) {
EventNewForm := form.Input{Values: r.PostForm, VErrors: form.ValidationErrors{}, CSRF: r.FormValue(csrfHKey)}
fmt.Println("name")
fmt.Println(r.FormValue(nameKey))
fmt.Println("name")
// _, s, _ := r.FormFile(fileKey)
// fmt.Println("FILE")
// fmt.Println(s.Filename)
// fmt.Println("FILE")
EventNewForm.ValidateRequiredFields(nameKey, locationKey, descriptionKey, datetimekey)
EventNewForm.MinLength(descriptionKey, 20)
EventNewForm.Date(datetimekey)
mh, _, err := r.FormFile(fileKey)
if err != nil || mh == nil {
EventNewForm.VErrors.Add(fileKey, "File error")
}
if !EventNewForm.IsValid() {
fmt.Println("last")
err := m.tmpl.ExecuteTemplate(w, "adminNewEvent.layout", EventNewForm)
if err != nil {
fmt.Println("hiiii")
fmt.Println(err)
}
return
}
if m.evrv.EventExists(r.FormValue(nameKey)) {
EventNewForm.VErrors.Add(nameKey, "This Event exists!")
err := m.tmpl.ExecuteTemplate(w, "adminNewEvent.layout", EventNewForm)
if err != nil {
fmt.Println("hiiii")
fmt.Println(err)
}
return
}
en := r.FormValue(nameKey)
c := r.FormValue(descriptionKey)
pri := r.FormValue(datetimekey)
vp := r.FormValue(locationKey)
mf, fh, _ := r.FormFile(fileKey)
defer mf.Close()
fname := fh.Filename
wd, err := os.Getwd()
path := filepath.Join(wd, "view", "assets", "images", fname)
image, err := os.Create(path)
fmt.Println(path)
if err != nil {
fmt.Println("error")
}
defer image.Close()
io.Copy(image, mf)
h := model.Event{
Name: en,
Description: c,
Location: vp,
Time: pri,
Image: fname,
}
event, errr := m.evrv.StoreEvent(&h)
fmt.Println("In ^^^^^^^^^^^^^^^^^^^")
fmt.Println(event)
if len(errr) > 0 {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
// tempo := struct{ Cid uint }{Cid: CID}
fmt.Println(m.tmpl.ExecuteTemplate(w, "adminNewEvent.layout", form.Input{CSRF: CSFRToken}))
}
}
func (m *AdminHandler) AdminHallUpdateList(w http.ResponseWriter, r *http.Request) {
halls1, _ := m.hsrv.Halls()
if m.isParsableFormPost(w, r) {
var EID uint
p := strings.Split(r.URL.Path, "/")
if len(p) == 1 {
//return defaultCode, p[0]
} else if len(p) > 1 {
code2, err2 := strconv.Atoi(p[4])
fmt.Println(err2)
fmt.Println(p)
if err2 == nil {
EID = uint(code2)
}
}
myhall, errr := m.hsrv.Hall(EID)
if errr != nil {
}
HallNewForm := form.Input{Values: r.PostForm, VErrors: form.ValidationErrors{}, CSRF: r.FormValue(csrfHKey)}
fmt.Println(r.FormValue(nameKey))
HallNewForm.ValidateRequiredFields(nameKey, capKey, priceKey, vipcapkey, vipKey)
HallNewForm.ValidateFieldsInteger(capKey, priceKey, vipcapkey, vipKey)
HallNewForm.ValidateFieldsRange(capKey, priceKey, vipcapkey, vipKey)
tempo1 := struct {
Halls []model.Hall
From form.Input
ID uint
Cid uint
}{Halls: halls1, From: HallNewForm, ID: EID, Cid: myhall.CinemaID}
if !HallNewForm.IsValid() {
err := m.tmpl.ExecuteTemplate(w, "halls.layout", tempo1)
if err != nil {
fmt.Println(err)
}
return
}
if m.hsrv.HallExists(r.FormValue(nameKey)) && r.FormValue(nameKey) != myhall.HallName {
HallNewForm.VErrors.Add(nameKey, "This Hall exists!")
tempo2 := struct {
Halls []model.Hall
From form.Input
ID uint
Cid uint
}{Halls: halls1, From: HallNewForm, ID: EID, Cid: myhall.CinemaID}
err := m.tmpl.ExecuteTemplate(w, "halls.layout", tempo2)
if err != nil {
fmt.Println(err)
}
return
}
hn := r.FormValue(nameKey)
c, _ := strconv.Atoi(r.FormValue(capKey))
pri, _ := strconv.Atoi(r.FormValue(priceKey))
vp, _ := strconv.Atoi(r.FormValue(vipKey))
wd, _ := strconv.Atoi(r.FormValue(vipcapkey))
h := model.Hall{
ID: myhall.ID,
HallName: hn,
Capacity: uint(c),
CinemaID: myhall.CinemaID,
Price: uint(pri),
VIPPrice: uint(vp),
VIPCapacity: uint(wd),
}
hh, errrr := m.hsrv.UpdateHall(&h)
if errrr != nil {
fmt.Println(errrr)
}
fmt.Println(hh)
if len(errrr) > 0 {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
halls, _ := m.hsrv.Halls()
tempo := struct {
Halls []model.Hall
From form.Input
ID uint
Cid uint
}{Halls: halls, From: HallNewForm, ID: EID, Cid: myhall.CinemaID}
fmt.Println(m.tmpl.ExecuteTemplate(w, "halls.layout", tempo))
}
}
func (m *AdminHandler) AdminEventUpdateList(w http.ResponseWriter, r *http.Request) {
events1, _ := m.evrv.Events()
r.ParseMultipartForm(0)
if m.isParsableFormPost(w, r) {
var EID uint
p := strings.Split(r.URL.Path, "/")
if len(p) == 1 {
//return defaultCode, p[0]
} else if len(p) > 1 {
code2, err2 := strconv.Atoi(p[4])
fmt.Println(err2)
fmt.Println(p)
if err2 == nil {
EID = uint(code2)
}
}
Myevent, errr := m.evrv.Event(EID)
if errr != nil {
}
EventNewForm := form.Input{Values: r.PostForm, VErrors: form.ValidationErrors{}, CSRF: r.FormValue(csrfHKey)}
fmt.Println(r.FormValue(nameKey))
// _, s, _ := r.FormFile(fileKey)
// fmt.Println("FILE")
// fmt.Println(s.Filename)
// fmt.Println("FILE")
EventNewForm.ValidateRequiredFields(nameKey, locationKey, descriptionKey, datetimekey)
EventNewForm.MinLength(descriptionKey, 20)
EventNewForm.Date(datetimekey)
tempo1 := struct {
Events []model.Event
From form.Input
ID uint
}{Events: events1, From: EventNewForm, ID: EID}
if !EventNewForm.IsValid() {
err := m.tmpl.ExecuteTemplate(w, "adminEventList.layout", tempo1)
if err != nil {
fmt.Println(err)
}
return
}
if m.evrv.EventExists(r.FormValue(nameKey)) && r.FormValue(nameKey) != Myevent.Name {
EventNewForm.VErrors.Add(nameKey, "This Event exists!")
tempo2 := struct {
Events []model.Event
From form.Input
ID uint
}{Events: events1, From: EventNewForm, ID: EID}
err := m.tmpl.ExecuteTemplate(w, "adminEventList.layout", tempo2)
if err != nil {
fmt.Println(err)
}
return
}
en := r.FormValue(nameKey)
c := r.FormValue(descriptionKey)
pri := r.FormValue(datetimekey)
vp := r.FormValue(locationKey)
mf, fh, sh := r.FormFile(fileKey)
if sh != nil || mf == nil {
EventNewForm.VErrors.Add(fileKey, "File error")
} else {
defer mf.Close()
fname := fh.Filename
if fname != Myevent.Image {
wd, err := os.Getwd()
path := filepath.Join(wd, "view", "assets", "images", fname)
image, err := os.Create(path)
fmt.Println(path)
if err != nil {
fmt.Println("error")
}
defer image.Close()
io.Copy(image, mf)
h := model.Event{
ID: Myevent.ID,
Name: en,
Description: c,
Location: vp,
Time: pri,
Image: fname,
}
jj, errrr := m.evrv.UpdateEvent(&h)
if len(errrr) > 0 {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
fmt.Println("In ^^^^^^^^^^^^^^^^^^^")
fmt.Println(jj)
}
}
events, _ := m.evrv.Events()
tempo := struct {
Events []model.Event
From form.Input
ID uint
}{Events: events, From: EventNewForm, ID: EID}
fmt.Println(m.tmpl.ExecuteTemplate(w, "adminEventList.layout", tempo))
}
}
func (m *AdminHandler) AdminEventList(w http.ResponseWriter, r *http.Request) {
events, errr := m.evrv.Events()
CSFRToken, _ := rtoken.GenerateCSRFToken(m.csrfSignKey)
tempo := struct {
Events []model.Event
From form.Input
}{Events: events, From: form.Input{CSRF: CSFRToken}}
if len(errr) > 0 {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
fmt.Println(m.tmpl.ExecuteTemplate(w, "adminEventList.layout", tempo))
}
func (m *AdminHandler) AdminHallsNew(w http.ResponseWriter, r *http.Request) {
var CID uint
p := strings.Split(r.URL.Path, "/")
if len(p) == 1 {
fmt.Println("in first if")
//return defaultCode, p[0]
} else if len(p) > 1 {
fmt.Println("..in first if")
code, err := strconv.Atoi(p[5])
fmt.Println(err)
fmt.Println(p)
fmt.Println(code)
if err == nil {
fmt.Println(".....in first if")
CID = uint(code)
}
}
if r.Method == http.MethodGet {
CSFRToken, err := rtoken.GenerateCSRFToken(m.csrfSignKey)
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
fmt.Println(m.tmpl.ExecuteTemplate(w, "adminNewHall.layout", form.Input{
CSRF: CSFRToken, Cid: CID}))
return
}
if m.isParsableFormPost(w, r) {
///Validate the form data
HallNewForm := form.Input{Values: r.PostForm, VErrors: form.ValidationErrors{}, CSRF: r.FormValue(csrfHKey), Cid: CID}
fmt.Println(r.FormValue("name"))
fmt.Println(r.FormValue("cap"))
fmt.Println(r.FormValue("price"))
fmt.Println(r.FormValue("name"))
fmt.Println(CID)
HallNewForm.ValidateRequiredFields(nameKey, capKey, priceKey, vipcapkey, vipKey)
HallNewForm.ValidateFieldsInteger(capKey, priceKey, vipcapkey, vipKey)
HallNewForm.ValidateFieldsRange(capKey, priceKey, vipcapkey, vipKey)
if !HallNewForm.IsValid() {
fmt.Println("last")
err := m.tmpl.ExecuteTemplate(w, "adminNewHall.layout", HallNewForm)
if err != nil {
fmt.Println("hiiii")
fmt.Println(err)
}
return
}
if m.hsrv.HallExists(r.FormValue(nameKey)) {
fmt.Println("secondemailexist")
HallNewForm.VErrors.Add(nameKey, "This HallName is already in use!")
err := m.tmpl.ExecuteTemplate(w, "adminNewHall.layout", HallNewForm)
if err != nil {
fmt.Println("hiiii")
fmt.Println(err)
}
return
}
hn := r.FormValue(nameKey)
c, _ := strconv.Atoi(r.FormValue(capKey))
pri, _ := strconv.Atoi(r.FormValue(priceKey))
vp, _ := strconv.Atoi(r.FormValue(vipKey))
wd, _ := strconv.Atoi(r.FormValue(vipcapkey))
h := model.Hall{
HallName: hn,
Capacity: uint(c),
CinemaID: CID,
Price: uint(pri),
VIPPrice: uint(vp),
VIPCapacity: uint(wd),
}
hall, errr := m.hsrv.StoreHall(&h)
fmt.Println("In ^^^^^^^^^^^^^^^^^^^")
fmt.Println(hall)
if len(errr) > 0 {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
// tempo := struct{ Cid uint }{Cid: CID}
fmt.Println(m.tmpl.ExecuteTemplate(w, "adminNewHall.layout", HallNewForm))
}
}
func (m *AdminHandler) AdminHalls(w http.ResponseWriter, r *http.Request) {
var CID uint
CSFRToken, _ := rtoken.GenerateCSRFToken(m.csrfSignKey)
p := strings.Split(r.URL.Path, "/")
if len(p) == 1 {
fmt.Println("in first if")
//return defaultCode, p[0]
} else if len(p) > 1 {
fmt.Println("..in first if")
code, err := strconv.Atoi(p[5])
fmt.Println(err)
fmt.Println(p)
fmt.Println(code)
if err == nil {
fmt.Println(".....in first if")
CID = uint(code)
}
}
halls, errr := m.hsrv.CinemaHalls(CID)
if len(errr) > 0 {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
tempo := struct {
Halls []model.Hall
Cid uint
From form.Input
}{Halls: halls, Cid: CID, From: form.Input{CSRF: CSFRToken}}
fmt.Println(m.tmpl.ExecuteTemplate(w, "halls.layout", tempo))
}
func (m *AdminHandler) AdminSchedule(w http.ResponseWriter, r *http.Request) {
var HallID int
p := strings.Split(r.URL.Path, "/")
if len(p) == 1 {
fmt.Println("in first if")
//return defaultCode, p[0]
} else if len(p) > 1 {
fmt.Println("..in first if")
code, err := strconv.Atoi(p[4])
fmt.Println(err)
fmt.Println(p)
fmt.Println(code)
if err == nil {
fmt.Println(".....in first if")
HallID = code
}
}
var All [][]model.ScheduleWithMovie
var SWM []model.ScheduleWithMovie
var err []error
var sm model.ScheduleWithMovie
var schedules []model.Schedule
//HallID, _ := strconv.Atoi(r.FormValue("hId"))
uHallID := uint(HallID)
Days := []string{"Monday", "Tuesday", "Wednsday", "Thursday", "Friday", "Saturday", "Sunday"}
for _, d := range Days {
schedules, err = m.ssrv.ScheduleHallDay(uHallID, d)
SWM = nil
for _, s := range schedules {
m, _, _ := controller.GetMovieDetails(s.MoviemID)
sm = model.ScheduleWithMovie{s, m.Title}
SWM = append(SWM, sm)
}
All = append(All, SWM)
}
hall, _ := m.hsrv.Hall(uint(HallID))
cinema, _ := m.csrv.Cinema(uint(hall.CinemaID))
tempo := struct {
HallId int
List [][]model.ScheduleWithMovie
Hall *model.Hall
Cinema *model.Cinema
}{
HallId: HallID,
List: All,
Hall: hall,
Cinema: cinema,
}
if len(err) > 0 {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
fmt.Println(tempo)
fmt.Println(m.tmpl.ExecuteTemplate(w, "adminScheduleList.layout", tempo))
}
func (m *AdminHandler) NewAdminScheduleHandler(w http.ResponseWriter, r *http.Request) {
var err error
if r.Method == "POST" {
m.NewAdminSchedulePost(w, r)
} else if r.Method == "GET" {
m.NewAdminSchedule(w, r)
}
if err != nil {
fmt.Println("hi")
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
}
}
func (m *AdminHandler) NewAdminSchedule(w http.ResponseWriter, r *http.Request) {
var MovieTitles *model.UpcomingMovies
var err error
var err2 error
var hallid int
CSFRToken, err := rtoken.GenerateCSRFToken(m.csrfSignKey)
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
p := strings.Split(r.URL.Path, "/")
if len(p) == 1 {
fmt.Println("in first if")
//return defaultCode, p[0]
} else if len(p) > 1 {
fmt.Println("..in first if")
code, err := strconv.Atoi(p[5])
fmt.Println(err)
fmt.Println(p)
fmt.Println(code)
if err == nil {
fmt.Println(".....in first if")
hallid = code
}
}
if r.FormValue("movie") != "" {
Movie := r.FormValue("movie")
fmt.Println(Movie)
MovieTitles, err2, err = controller.SearchMovie(Movie)
if err == nil || err2 == nil {
fmt.Println("did seatch")
fmt.Println(MovieTitles)
}
} else {
fmt.Println("empty")
movie := r.FormValue("movie")
fmt.Println(movie)
}
convid, _ := strconv.Atoi(r.FormValue("id"))
//hallid, _ := strconv.Atoi(r.FormValue("hId"))
hall, _ := m.hsrv.Hall(uint(hallid))
cinema, _ := m.csrv.Cinema(uint(hall.CinemaID))
tempo := struct {
M *model.UpcomingMovies
MovieN string
MovieID int
HallID int
Hall *model.Hall
From form.Input
Cinema *model.Cinema
}{
M: MovieTitles,
MovieN: r.FormValue("moviename"),
MovieID: convid,
HallID: hallid,
Hall: hall,
From: form.Input{CSRF: CSFRToken},
Cinema: cinema,
}
fmt.Println(m.tmpl.ExecuteTemplate(w, "adminNewSchedule.layout", tempo))
}
func (m *AdminHandler) NewAdminSchedulePost(w http.ResponseWriter, r *http.Request) {
var hallid int
p := strings.Split(r.URL.Path, "/")
if len(p) == 1 {
fmt.Println("in first if")
//return defaultCode, p[0]
} else if len(p) > 1 {
fmt.Println("..in first if")
code, err := strconv.Atoi(p[5])
fmt.Println(err)
fmt.Println(p)
fmt.Println(code)
if err == nil {
fmt.Println(".....in first if")
hallid = code
}
}
if m.isParsableFormPost(w, r) {
var a *model.Schedule
var movie *model.Moviem
ScheduleNewForm := form.Input{Values: r.PostForm, VErrors: form.ValidationErrors{}, CSRF: r.FormValue(csrfHKey)}
hall, _ := m.hsrv.Hall(uint(hallid))
cinema, _ := m.csrv.Cinema(uint(hall.CinemaID))
MID, _ := strconv.Atoi(r.FormValue("mid"))
fmt.Println("printing mid", MID)
Time := r.FormValue("time")
fmt.Println("printing time", Time)
DAy := r.FormValue("day")
fmt.Println("printing day", DAy)
Dimen := r.FormValue("3or2d")
fmt.Println("printing day", Dimen)
ScheduleNewForm.ValidateRequiredFields("time", "day", "3or2d")
ScheduleNewForm.Date("time")
tempo := struct {
M *model.UpcomingMovies
MovieN string
MovieID int
HallID int
Hall *model.Hall
From form.Input
Cinema *model.Cinema
}{
M: nil,
MovieN: "",
MovieID: 0,
HallID: hallid,
Hall: hall,
From: ScheduleNewForm,
Cinema: cinema,
}
if !ScheduleNewForm.IsValid() {
fmt.Println("last")
err := m.tmpl.ExecuteTemplate(w, "adminNewSchedule.layout", tempo)
if err != nil {
fmt.Println("hiiii")
fmt.Println(err)
}
return
}
a = &model.Schedule{MoviemID: MID, StartingTime: Time, Dimension: Dimen, HallID: hallid, Day: DAy}
movie = &model.Moviem{TmdbID: MID}
if MID != 0 && Time != "" && DAy != "" && hallid != 0 {
m.ssrv.StoreSchedule(a)
m.msrv.StoreMovie(movie)
}
fmt.Println(m.tmpl.ExecuteTemplate(w, "adminNewSchedule.layout", tempo))
}
fmt.Println("Error")
}
func (m *AdminHandler) isParsableFormPost(w http.ResponseWriter, r *http.Request) bool {
err := r.ParseForm()
if err != nil {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return false
}
fmt.Println("parse")
fmt.Println(r.Method == http.MethodPost)
fmt.Println(hash.ParseForm(w, r))
fmt.Println(r.FormValue(csrfHKey))
fmt.Println(rtoken.IsCSRFValid(r.FormValue(csrfHKey), m.csrfSignKey))
return r.Method == http.MethodPost &&
hash.ParseForm(w, r) &&
rtoken.IsCSRFValid(r.FormValue(csrfHKey), m.csrfSignKey)
}
|
package seeders
import (
"math/rand"
"time"
"github.com/agusbasari29/Skilltest-RSP-Akselerasi-2-Backend-Agus-Basari/entity"
"github.com/bxcodec/faker/v3"
)
type TransactionsSeeders struct {
StatusPayment string `faker:"oneof: passed, failed"`
}
func TransactionsSeedersUp(number int) {
seeder := TransactionsSeeders{}
trx := entity.Transaction{}
creator, _ := userRepo.GetUserByRole(entity.Users{Role: "creator"})
participant, _ := userRepo.GetUserByRole(entity.Users{Role: "participant"})
events := eventRepo.GetEventByStatus("release")
var payment entity.StatusPayment
for i := 0; i < number; i++ {
j := rand.Intn(len(creator))
k := rand.Intn(len(participant))
l := rand.Intn(len(events))
m := rand.Intn(3)
err := faker.FakeData(&seeder)
if err != nil {
panic(err)
}
switch m {
case 1:
payment = "passed"
case 2:
payment = "failed"
}
trx.StatusPayment = payment
trx.Amount = events[l].Price
trx.EventId = int(events[l].ID)
trx.CreatorId = int(creator[j].ID)
trx.ParticipantId = int(participant[k].ID)
trx.CreatedAt = time.Now()
trxRepo.InsertTransaction(trx)
}
}
|
package main
import (
. "ast"
cg "backend/codeGeneration"
fw "backend/filewriter"
"fmt"
"io/ioutil"
"os"
"parser"
"path/filepath"
)
const SYNTAX_ERROR = 100
const SEMANTIC_ERROR = 200
func main() {
armList := &fw.ARMList{}
file := os.Args[1] // index 1 is file path
b, err := ioutil.ReadFile(file)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
s := string(b)
root, err := parser.ParseFile(file, s)
if err != nil {
os.Exit(SYNTAX_ERROR)
}
fmt.Println(root)
errs := root.SemanticCheck()
if errs != nil {
for _, str := range errs {
fmt.Println(str)
}
os.Exit(SEMANTIC_ERROR)
}
root.SymbolTable.PrintChildren()
filename := filepath.Base(file)
ext := filepath.Ext(filename)
fileARM := filename[0:len(filename)-len(ext)] + ".s"
codeGen := cg.ConstructCodeGenerator(root, armList, root.SymbolTable)
codeGen.GenerateCode()
for _, instr := range *armList {
fmt.Print(instr)
}
armList.WriteToFile(fileARM)
}
|
package cloudflare
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestResourceProperties(t *testing.T) {
testCases := map[string]struct {
container *ResourceContainer
expectedRoute string
expectedType string
expectedIdentifier string
}{
account: {
container: AccountIdentifier("abcd1234"),
expectedRoute: accounts,
expectedType: account,
expectedIdentifier: "abcd1234",
},
zone: {
container: ZoneIdentifier("abcd1234"),
expectedRoute: zones,
expectedType: zone,
expectedIdentifier: "abcd1234",
},
user: {
container: UserIdentifier("abcd1234"),
expectedRoute: user,
expectedType: user,
expectedIdentifier: "abcd1234",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
setup()
defer teardown()
assert.Equal(t, tc.container.Level.String(), tc.expectedRoute)
assert.Equal(t, tc.container.Type.String(), tc.expectedType)
assert.Equal(t, tc.container.Identifier, tc.expectedIdentifier)
})
}
}
func TestResourcURLFragment(t *testing.T) {
tests := map[string]struct {
container *ResourceContainer
want string
}{
"account resource": {container: AccountIdentifier("foo"), want: "accounts/foo"},
"zone resource": {container: ZoneIdentifier("foo"), want: "zones/foo"},
// this is pretty well deprecated in favour of `AccountIdentifier` but
// here for completeness.
"user level resource": {container: UserIdentifier("foo"), want: "user"},
"missing level resource": {container: &ResourceContainer{Level: "", Identifier: "foo"}, want: "foo"},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
got := tc.container.URLFragment()
assert.Equal(t, tc.want, got)
})
}
}
|
package cls
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
type LogSets struct {
LogSets []LogSet `json:"logsets"`
}
type LogSet struct {
LogSetID string `json:"logset_id"`
LogSetName string `json:"logset_name"`
CreateTime string `json:"create_time"`
Period int `json:"period"`
TopicsNumber int `json:"topics_number"`
}
func (cls *ClSCleint) CreateLogSet(logSetName string, period int) (string, error) {
data := fmt.Sprintf("{\"logset_name\":\"%s\",\"period\":%d}", logSetName, period)
var headers = url.Values{"Host": {fmt.Sprintf("%s", cls.Host)}, "User-Agent": {"AuthSDK"}}
body := bytes.NewBuffer([]byte(data))
sig := Signature(fmt.Sprintf("%s", cls.SecretId), fmt.Sprintf("%s", cls.SecretKey),
"POST", "/logset", nil, headers, 300)
req, err := http.NewRequest("POST", fmt.Sprintf("http://%s/logset", cls.Host), body)
if err != nil {
return "", err
}
req.Header.Add("Authorization", sig)
req.Header.Add("Host", fmt.Sprintf("%s", cls.Host))
req.Header.Add("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
logSet := LogSet{}
bod, err := ioutil.ReadAll(resp.Body)
if err := json.Unmarshal(bod, &logSet); err != nil {
fmt.Println(err)
return "", err
}
return logSet.LogSetID, nil
}
func (cls *ClSCleint) GetLogSet(logSetID string) (logSet LogSet, err error) {
var params = url.Values{"logset_id": {fmt.Sprintf("%s", logSetID)}}
var headers = url.Values{"Host": {fmt.Sprintf("%s", cls.Host)}, "User-Agent": {"AuthSDK"}}
sig := Signature(fmt.Sprintf("%s", cls.SecretId), fmt.Sprintf("%s", cls.SecretKey),
"GET", "/logset", params, headers, 300)
req, err := http.NewRequest("GET", fmt.Sprintf("http://%s/logset?logset_id=%s", cls.Host, logSetID), nil)
if err != nil {
return logSet, err
}
req.Header.Add("Authorization", sig)
req.Header.Add("Host", fmt.Sprintf("%s", cls.Host))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return logSet, err
}
body, err := ioutil.ReadAll(resp.Body)
if err := json.Unmarshal(body, &logSet); err != nil {
fmt.Println(err)
return logSet, err
}
return logSet, nil
}
func (cls *ClSCleint) GetLogSets() (logSets LogSets, err error) {
var headers = url.Values{"Host": {fmt.Sprintf("%s", cls.Host)}, "User-Agent": {"AuthSDK"}}
sig := Signature(fmt.Sprintf("%s", cls.SecretId), fmt.Sprintf("%s", cls.SecretKey),
"GET", "/logsets", nil, headers, 300)
req, err := http.NewRequest("GET", fmt.Sprintf("http://%s/logsets", cls.Host), nil)
if err != nil {
return logSets, err
}
req.Header.Add("Authorization", sig)
req.Header.Add("Host", fmt.Sprintf("%s", cls.Host))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return logSets, err
}
body, err := ioutil.ReadAll(resp.Body)
if err := json.Unmarshal(body, &logSets); err != nil {
return logSets, err
}
return logSets, nil
}
func (cls *ClSCleint) UpdateLogSet(logSetID, logSetName string, period int) error {
data := fmt.Sprintf("{\"logset_id\":\"%s\",\"logset_name\":\"%s\",\"period\":%d}", logSetID, logSetName, period)
var headers = url.Values{"Host": {fmt.Sprintf("%s", cls.Host)}, "User-Agent": {"AuthSDK"}}
body := bytes.NewBuffer([]byte(data))
sig := Signature(fmt.Sprintf("%s", cls.SecretId), fmt.Sprintf("%s", cls.SecretKey),
"PUT", "/logset", nil, headers, 300)
req, err := http.NewRequest("PUT", fmt.Sprintf("http://%s/logset", cls.Host), body)
if err != nil {
return err
}
req.Header.Add("Authorization", sig)
req.Header.Add("Host", fmt.Sprintf("%s", cls.Host))
req.Header.Add("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return fmt.Errorf("%d", resp.StatusCode)
}
return nil
}
func (cls *ClSCleint) DeleteLogSet(logSetID string) error {
var params = url.Values{"logset_id": {fmt.Sprintf("%s", logSetID)}}
var headers = url.Values{"Host": {fmt.Sprintf("%s", cls.Host)}, "User-Agent": {"AuthSDK"}}
sig := Signature(fmt.Sprintf("%s", cls.SecretId), fmt.Sprintf("%s", cls.SecretKey),
"DELETE", "/logset", params, headers, 300)
req, err := http.NewRequest("DELETE", fmt.Sprintf("http://%s/logset?logset_id=%s", cls.Host, logSetID), nil)
if err != nil {
return err
}
req.Header.Add("Authorization", sig)
req.Header.Add("Host", fmt.Sprintf("%s", cls.Host))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
return err
}
fmt.Println(string(body))
return nil
}
|
package protobuf
import (
"encoding"
)
var generators = newInterfaceRegistry()
// InterfaceMarshaler is used to differentiate implementations of an
// interface when encoding/decoding
type InterfaceMarshaler interface {
encoding.BinaryMarshaler
MarshalID() [8]byte
}
// InterfaceGeneratorFunc generates an instance of the implementation
// of an interface
type InterfaceGeneratorFunc func() interface{}
// GeneratorID is the key used to map the generator functions
type GeneratorID [8]byte
type generatorRegistry struct {
generators map[GeneratorID]InterfaceGeneratorFunc
}
func newInterfaceRegistry() *generatorRegistry {
return &generatorRegistry{
generators: make(map[GeneratorID]InterfaceGeneratorFunc),
}
}
// register gets the type tag and map it to the generator function
func (ir *generatorRegistry) register(g InterfaceGeneratorFunc) {
val, ok := g().(InterfaceMarshaler)
if !ok {
panic("Implementation of the interface must fulfilled InterfaceMarshaler")
}
key := val.MarshalID()
ir.generators[key] = g
}
// get returns the generator associated with the tag
func (ir *generatorRegistry) get(key GeneratorID) InterfaceGeneratorFunc {
g, _ := ir.generators[key]
return g
}
// RegisterInterface registers the generator to be used to decode
// the type generated by the function
func RegisterInterface(f InterfaceGeneratorFunc) {
generators.register(f)
}
|
package boshio_test
import (
"errors"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/concourse/bosh-io-stemcell-resource/boshio"
"github.com/concourse/bosh-io-stemcell-resource/fakes"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
type EOFReader struct{}
func (e EOFReader) Read(p []byte) (int, error) {
return 0, io.ErrUnexpectedEOF
}
var _ = Describe("Boshio", func() {
var (
httpClient boshio.HTTPClient
client *boshio.Client
ranger *fakes.Ranger
bar *fakes.Bar
forceRegular bool
)
BeforeEach(func() {
ranger = &fakes.Ranger{}
bar = &fakes.Bar{}
forceRegular = false
httpClient = boshio.NewHTTPClient(boshioServer.URL(), 800*time.Millisecond)
client = boshio.NewClient(httpClient, bar, ranger, forceRegular)
})
Describe("GetStemcells", func() {
It("fetches all stemcells for a given name", func() {
boshioServer.Start()
stemcells, err := client.GetStemcells("some-light-stemcell")
Expect(err).NotTo(HaveOccurred())
Expect(stemcells).To(Equal(boshio.Stemcells{
{
Name: "a stemcell",
Version: "some version",
Light: &boshio.Metadata{
URL: serverPath("path/to/light-different-stemcell.tgz"),
Size: 100,
MD5: "qqqq",
SHA1: "2222",
SHA256: "4444",
},
},
}))
})
Context("when an error occurs", func() {
Context("when bosh.io responds with a non-200", func() {
It("returns an error", func() {
boshioServer.LightAPIHandler = func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}
boshioServer.Start()
_, err := client.GetStemcells("some-light-stemcell")
Expect(err).To(MatchError("failed fetching metadata - boshio returned: 500"))
})
})
Context("when the get fails", func() {
XIt("returns an error", func() {
_, err := client.GetStemcells("some-light-stemcell")
Expect(err).To(MatchError(ContainSubstring("invalid URL escape")))
})
})
Context("when the response is invalid json", func() {
It("returns an error", func() {
boshioServer.LightAPIHandler = func(w http.ResponseWriter, req *http.Request) {
w.Write([]byte(`%%%%%`))
}
boshioServer.Start()
_, err := client.GetStemcells("some-light-stemcell")
Expect(err).To(MatchError(ContainSubstring("invalid character")))
})
})
})
})
Describe("WriteMetadata", func() {
var fileLocation *os.File
BeforeEach(func() {
var err error
fileLocation, err = ioutil.TempFile("", "")
Expect(err).NotTo(HaveOccurred())
})
AfterEach(func() {
err := os.Remove(fileLocation.Name())
Expect(err).NotTo(HaveOccurred())
})
It("writes the url to disk", func() {
err := client.WriteMetadata(boshio.Stemcell{Light: &boshio.Metadata{URL: "http://example.com"}}, "url", fileLocation)
Expect(err).NotTo(HaveOccurred())
url, err := ioutil.ReadFile(fileLocation.Name())
Expect(err).NotTo(HaveOccurred())
Expect(string(url)).To(Equal("http://example.com"))
})
It("writes the sha1 to disk", func() {
err := client.WriteMetadata(boshio.Stemcell{Regular: &boshio.Metadata{SHA1: "2222"}}, "sha1", fileLocation)
Expect(err).NotTo(HaveOccurred())
sha1, err := ioutil.ReadFile(fileLocation.Name())
Expect(err).NotTo(HaveOccurred())
Expect(string(sha1)).To(Equal("2222"))
})
It("writes the sha256 to disk", func() {
err := client.WriteMetadata(boshio.Stemcell{Regular: &boshio.Metadata{SHA256: "4444"}}, "sha256", fileLocation)
Expect(err).NotTo(HaveOccurred())
sha256, err := ioutil.ReadFile(fileLocation.Name())
Expect(err).NotTo(HaveOccurred())
Expect(string(sha256)).To(Equal("4444"))
})
It("writes the version to disk", func() {
err := client.WriteMetadata(boshio.Stemcell{Version: "some version", Regular: &boshio.Metadata{}}, "version", fileLocation)
Expect(err).NotTo(HaveOccurred())
version, err := ioutil.ReadFile(fileLocation.Name())
Expect(err).NotTo(HaveOccurred())
Expect(string(version)).To(Equal("some version"))
})
Context("when an error occurs", func() {
Context("when url writer fails", func() {
It("returns an error", func() {
err := client.WriteMetadata(boshio.Stemcell{Name: "some-heavy-stemcell", Regular: &boshio.Metadata{}}, "url", fakes.NoopWriter{})
Expect(err).To(MatchError("explosions"))
})
})
Context("when sha1 writer fails", func() {
It("returns an error", func() {
err := client.WriteMetadata(boshio.Stemcell{Name: "some-heavy-stemcell", Regular: &boshio.Metadata{}}, "sha1", fakes.NoopWriter{})
Expect(err).To(MatchError("explosions"))
})
})
Context("when version writer fails", func() {
It("returns an error", func() {
err := client.WriteMetadata(boshio.Stemcell{Name: "some-heavy-stemcell", Regular: &boshio.Metadata{}}, "version", fakes.NoopWriter{})
Expect(err).To(MatchError("explosions"))
})
})
})
})
Describe("DownloadStemcell", func() {
var stubStemcell boshio.Stemcell
BeforeEach(func() {
ranger.BuildRangeReturns([]string{
"0-9", "10-19", "20-29",
"30-39", "40-49", "50-59",
"60-69", "70-79", "80-89",
"90-99",
}, nil)
stubStemcell = boshio.Stemcell{
Name: "different-stemcell",
Version: "2222",
Regular: &boshio.Metadata{
URL: serverPath("path/to/light-different-stemcell.tgz"),
Size: 100,
MD5: "qqqq",
SHA1: "5f8d38fd6bb6fd12fcaa284c7132b64cbb20ea4e",
},
}
})
It("writes the stemcell to the provided location", func() {
boshioServer.Start()
location, err := ioutil.TempDir("", "")
Expect(err).NotTo(HaveOccurred())
err = client.DownloadStemcell(stubStemcell, location, false)
Expect(err).NotTo(HaveOccurred())
content, err := ioutil.ReadFile(filepath.Join(location, "stemcell.tgz"))
Expect(err).NotTo(HaveOccurred())
Expect(string(content)).To(Equal("this string is definitely not long enough to be 100 bytes but we get it there with a little bit of.."))
})
It("uses the stemcell filename from bosh.io when the preserveFileName param is set to true", func() {
boshioServer.Start()
location, err := ioutil.TempDir("", "")
Expect(err).NotTo(HaveOccurred())
err = client.DownloadStemcell(stubStemcell, location, true)
Expect(err).NotTo(HaveOccurred())
content, err := ioutil.ReadFile(filepath.Join(location, "light-different-stemcell.tgz"))
Expect(err).NotTo(HaveOccurred())
Expect(string(content)).To(Equal("this string is definitely not long enough to be 100 bytes but we get it there with a little bit of.."))
})
})
Context("when an error occurs", func() {
var stubStemcell boshio.Stemcell
BeforeEach(func() {
stubStemcell = boshio.Stemcell{
Name: "different-stemcell",
Version: "2222",
Regular: &boshio.Metadata{
URL: serverPath("path/to/light-different-stemcell.tgz"),
Size: 100,
MD5: "qqqq",
SHA1: "2222",
},
}
})
Context("when an io error occurs", func() {
It("retries the request", func() {
httpClient := &fakes.HTTPClient{}
ranger.BuildRangeReturns([]string{"0-9"}, nil)
var (
responses []*http.Response
httpErrors []error
)
httpClient.DoStub = func(req *http.Request) (*http.Response, error) {
count := httpClient.DoCallCount() - 1
return responses[count], httpErrors[count]
}
responses = []*http.Response{
{StatusCode: http.StatusOK, Body: nil, ContentLength: 10, Request: &http.Request{URL: &url.URL{Scheme: "https", Host: "example.com", Path: "hello"}}},
{StatusCode: http.StatusPartialContent, Body: ioutil.NopCloser(EOFReader{})},
{StatusCode: http.StatusPartialContent, Body: ioutil.NopCloser(strings.NewReader("hello good"))},
}
httpErrors = []error{nil, nil, nil}
client = boshio.NewClient(httpClient, bar, ranger, forceRegular)
location, err := ioutil.TempDir("", "")
Expect(err).NotTo(HaveOccurred())
stubStemcell := boshio.Stemcell{
Name: "different-stemcell",
Version: "2222",
Regular: &boshio.Metadata{
URL: serverPath("path/to/light-different-stemcell.tgz"),
Size: 100,
MD5: "qqqq",
SHA1: "1c36c7afa4e21e2ccc0c386f790560672534723a",
},
}
err = client.DownloadStemcell(stubStemcell, location, false)
Expect(err).NotTo(HaveOccurred())
content, err := ioutil.ReadFile(filepath.Join(location, "stemcell.tgz"))
Expect(err).NotTo(HaveOccurred())
Expect(string(content)).To(Equal("hello good"))
})
})
Context("when the HEAD request cannot be constructed", func() {
It("returns an error", func() {
stubStemcell := boshio.Stemcell{
Name: "different-stemcell",
Version: "2222",
Regular: &boshio.Metadata{
URL: "%%%%",
Size: 100,
MD5: "qqqq",
SHA1: "1c36c7afa4e21e2ccc0c386f790560672534723a",
},
}
err := client.DownloadStemcell(stubStemcell, "", false)
Expect(err).To(MatchError(ContainSubstring("failed to construct HEAD request:")))
})
})
Context("when the range cannot be constructed", func() {
It("returns an error", func() {
ranger.BuildRangeReturns([]string{}, errors.New("failed to build a range"))
boshioServer.Start()
err := client.DownloadStemcell(stubStemcell, "", true)
Expect(err).To(MatchError("failed to build a range"))
})
})
Context("when the stemcell file cannot be created", func() {
It("returns an error", func() {
boshioServer.Start()
location, err := ioutil.TempFile("", "")
Expect(err).NotTo(HaveOccurred())
defer os.RemoveAll(location.Name())
err = location.Close()
Expect(err).NotTo(HaveOccurred())
err = client.DownloadStemcell(stubStemcell, location.Name(), true)
Expect(err).To(MatchError(ContainSubstring("not a directory")))
})
})
Context("when the sha1 cannot be verified", func() {
It("returns an error", func() {
boshioServer.Start()
location, err := ioutil.TempDir("", "")
Expect(err).NotTo(HaveOccurred())
err = client.DownloadStemcell(stubStemcell, location, true)
Expect(err).To(MatchError("computed sha1 da39a3ee5e6b4b0d3255bfef95601890afd80709 did not match expected sha1 of 2222"))
})
})
Context("when the sha256 cannot be verified", func() {
It("returns an error", func() {
stubStemcell.Regular.SHA256 = "4444"
boshioServer.Start()
location, err := ioutil.TempDir("", "")
Expect(err).NotTo(HaveOccurred())
err = client.DownloadStemcell(stubStemcell, location, true)
Expect(err).To(MatchError("computed sha256 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 did not match expected sha256 of 4444"))
})
})
Context("when the get request is not successful", func() {
It("returns an error", func() {
ranger.BuildRangeReturns([]string{"0-9"}, nil)
boshioServer.TarballHandler = func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}
boshioServer.Start()
location, err := ioutil.TempDir("", "")
Expect(err).NotTo(HaveOccurred())
err = client.DownloadStemcell(stubStemcell, location, true)
Expect(err).To(MatchError(ContainSubstring("failed to download stemcell - boshio returned 500")))
})
})
})
})
|
package util
import (
"log"
"regexp"
)
const NameRegexFragment = `(([a-zA-Z][a-zA-Z0-9_\-\.]*[a-zA-Z0-9])|([a-zA-Z]))`
const NameRegexPattern = `^` + NameRegexFragment + `$`
var NameRegex = regexp.MustCompile(NameRegexPattern)
const URIRegexPattern = `^(` + NameRegexFragment + `[\/]?)*$`
var URIRegex = regexp.MustCompile(URIRegexPattern)
const VarNameRegexPattern = `^(([a-zA-Z][a-zA-Z0-9_\-\.]*[a-zA-Z0-9])|([a-zA-Z]))$`
const VarSecretNameAndSecretsFolderNamePattern = `^(([a-zA-Z][a-zA-Z0-9_\-\./]*[a-zA-Z0-9/])|([a-zA-Z/]))$` //nolint:gosec
var VarNameRegex = regexp.MustCompile(VarNameRegexPattern)
const RefRegexFragment = `(([a-zA-Z0-9][a-zA-Z0-9_\-\.]*[a-zA-Z0-9])|([a-zA-Z0-9]))`
const RefRegexPattern = `^` + RefRegexFragment + `$`
var RefRegex = regexp.MustCompile(RefRegexPattern)
const (
RegexPattern = NameRegexPattern
VarRegexPattern = VarNameRegexPattern
)
var (
reg *regexp.Regexp
varreg *regexp.Regexp
varSNameAndSFName *regexp.Regexp
)
func init() {
var err error
reg, err = regexp.Compile(RegexPattern)
if err != nil {
log.Fatal(err.Error())
}
varreg, err = regexp.Compile(VarRegexPattern)
if err != nil {
log.Fatal(err.Error())
}
varSNameAndSFName, err = regexp.Compile(VarSecretNameAndSecretsFolderNamePattern)
if err != nil {
log.Fatal(err.Error())
}
}
// MatchesRegex responds true if the provided string matches the
// RegexPattern constant defined in this package.
func MatchesRegex(s string) bool {
return reg.MatchString(s)
}
func MatchesVarRegex(s string) bool {
return varreg.MatchString(s)
}
func MatchesVarSNameAndSFName(s string) bool {
return varSNameAndSFName.MatchString(s)
}
|
// Copyright 2013 Walter Schulze
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package funcs
import (
"strings"
"time"
)
//Now returns a new now function.
func Now() Int {
return &now{}
}
type now struct{}
func (this *now) Eval() (int64, error) {
return time.Now().UnixNano(), nil
}
func (this *now) Hash() uint64 {
return Hash("now")
}
func (this *now) Compare(that Comparable) int {
if this.Hash() != that.Hash() {
if this.Hash() < that.Hash() {
return -1
}
return 1
}
if _, ok := that.(*now); ok {
return 0
}
return strings.Compare(this.String(), that.String())
}
func (this *now) String() string {
return "now()"
}
func (this *now) HasVariable() bool { return true }
func init() {
Register("now", Now)
}
|
package repositories
import (
"database/sql"
"errors"
"fmt"
"log"
"ocg-be/database"
"ocg-be/models"
"reflect"
)
type ProductStorage struct {
}
type RequestGetProductByCollectionId struct {
CollectionId int `json:"collection_id"`
Limit int `json:"limit"`
Offset int `json:"offset"`
Page int `json:"page"`
Sort string `json:"sort"`
Order string `json:"order"`
Search string `json:"search"`
}
func (p *ProductStorage) Count(search string) int64 {
var rows *sql.Rows
var err error
rows, err = database.DB.Query("SELECT COUNT(*) FROM products WHERE name LIKE ?", search)
if err != nil {
log.Println(err)
}
var total int64
for rows.Next() {
rows.Scan(&total)
}
return total
}
func (p *ProductStorage) Take(limit int, offset int, orderBy string, sort string, search string) interface{} {
var products []models.Product
var rows *sql.Rows
var err error
qtext := fmt.Sprintf("SELECT * FROM products WHERE name LIKE ? ORDER BY %s %s LIMIT ? OFFSET ? ", orderBy, sort)
rows, err = database.DB.Query(qtext, search, limit, offset)
if err != nil {
log.Println(err)
return nil
}
for rows.Next() {
var product models.Product
err = rows.Scan(&product.Id, &product.Name, &product.Handle, &product.Description, &product.Price, &product.Trademark)
if err != nil {
log.Println(err)
return nil
}
var image ImageStorage
product.Image = image.Take(int64(product.Id))
products = append(products, product)
}
return products
}
func (p *ProductStorage) Add(product *models.Product) (int, error) {
_, err := database.DB.Query("INSERT INTO products VALUES (?,?, ?, ?, ?, ?)", product.Id, product.Name, product.Handle, product.Description, product.Price, product.Trademark)
if err != nil {
product = nil
fmt.Println(err)
return 0, errors.New("hinh nhu bi trung ten san pham anh oi")
}
rows, _ := database.DB.Query("SELECT id FROM products ORDER BY id DESC LIMIT 1")
if rows.Next() {
err = rows.Scan(&product.Id)
if err != nil {
product = nil
fmt.Println(err)
return 0, err
}
}
return product.Id, nil
}
func (p *ProductStorage) GetByHandle(handle string) (models.Product, error) {
var product models.Product
rows, err := database.DB.Query("SELECT * from products WHERE handle = ?", handle)
if err != nil {
fmt.Println(err)
return product, err
}
if rows.Next() {
err = rows.Scan(&product.Id, &product.Name, &product.Handle, &product.Description, &product.Price, &product.Trademark)
if err != nil {
fmt.Println(err)
return product, err
}
} else {
return product, errors.New("khong tim thay san pham")
}
var image ImageStorage
product.Image = image.Take(int64(product.Id))
return product, nil
}
func (p *ProductStorage) DeleteById(id int) error {
_, err := database.DB.Query("DELETE FROM collection_product WHERE product_id=?", id)
if err != nil {
log.Println(err)
return err
}
_, err = database.DB.Query("DELETE FROM products WHERE id=?", id)
if err != nil {
log.Println(err)
return err
}
return nil
}
func (p *ProductStorage) UpdateProduct(product *models.Product) (*models.Product, error) {
log.Println(product.Id)
fmt.Println(reflect.TypeOf(product.Id))
if product.Price != 0 {
log.Println("price")
_, err := database.DB.Query("UPDATE products SET price=? WHERE id=?", product.Price, product.Id)
if err != nil {
return nil, err
}
}
if product.Description != "" {
_, err := database.DB.Query("UPDATE products SET description=? WHERE id=?", product.Description, product.Id)
if err != nil {
return nil, err
}
}
if product.Name != "" {
log.Println("name")
_, err := database.DB.Query("UPDATE products SET name=? WHERE id=?", product.Name, product.Id)
if err != nil {
return nil, err
}
}
if product.Trademark != "" {
_, err := database.DB.Query("UPDATE products SET trade_mark=? WHERE id=?", product.Trademark, product.Id)
if err != nil {
return nil, err
}
}
return product, nil
}
func (p *RequestGetProductByCollectionId) Count(search string) int64 {
var rows *sql.Rows
var err error
rows, err = database.DB.Query("SELECT COUNT(*) FROM `products` LEFT JOIN collection_product ON collection_product.product_id=products.id WHERE collection_product.collection_id= ?", p.CollectionId)
if err != nil {
log.Println(err)
}
var total int64
for rows.Next() {
rows.Scan(&total)
}
return total
}
func (p *RequestGetProductByCollectionId) Take(limit int, offset int, orderBy string, sort string, search string) interface{} {
var products []models.Product
var rows *sql.Rows
var err error
qtext := fmt.Sprintf("SELECT products.* FROM products LEFT JOIN collection_product ON collection_product.product_id=products.id WHERE collection_product.collection_id= ? ORDER BY %s %s LIMIT ? OFFSET ? ", orderBy, sort)
rows, err = database.DB.Query(qtext, p.CollectionId, limit, offset)
if err != nil {
log.Println(err)
return nil
}
for rows.Next() {
var product models.Product
err = rows.Scan(&product.Id, &product.Name, &product.Handle, &product.Description, &product.Price, &product.Trademark)
if err != nil {
log.Println(err)
return nil
}
var image ImageStorage
product.Image = image.Take(int64(product.Id))
products = append(products, product)
}
return products
}
|
package audit
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
api "nighthawkapi/api/core"
"nighthawkapi/api/handlers/config"
"strconv"
elastic "gopkg.in/olivere/elastic.v5"
"github.com/gorilla/mux"
)
type ReturnBucket struct {
Key string `json:"key"`
DocCount int64 `json:"doc_count"`
}
type CaseBucket struct {
KeyAsString string `json:"key_as_string"`
DocCount int64 `json:"doc_count"`
}
type FilterOn struct {
ColId string `json:"colId"`
Filter struct {
FilterQuery interface{} `json:"filter"`
FilterType string `json:"filterType"`
} `json:"filterOn"`
}
func GetDocById(w http.ResponseWriter, r *http.Request) {
r.Header.Set("Content-Type", "application/json; charset=UTF-8")
var (
method, ret string
client *elastic.Client
query elastic.Query
cases *elastic.SearchResult
conf *config.ConfigVars
err error
)
vars := mux.Vars(r)
conf, err = config.ReadConfFile()
if err != nil {
api.LogError(api.DEBUG, err)
}
if conf.Elastic.Elastic_ssl {
method = api.HTTPS
} else {
method = api.HTTP
}
client, err = elastic.NewClient(elastic.SetURL(fmt.Sprintf("%s%s:%d", method, conf.Elastic.Elastic_server, conf.Elastic.Elastic_port)))
if err != nil {
api.LogError(api.DEBUG, err)
}
query = elastic.NewTermQuery("_id", vars["doc_id"])
cases, err = client.Search().
Index(conf.Elastic.Elastic_index).
Query(query).
Size(1).
Do(context.Background())
if err != nil {
api.HttpFailureMessage(fmt.Sprintf("Elasticsearch Error: %s", err.Error()))
api.LogError(api.DEBUG, err)
return
}
ret = api.HttpSuccessMessage("200", &cases.Hits.Hits[0], cases.TotalHits())
api.LogDebug(api.DEBUG, fmt.Sprintf("[+] GET /show/doc/%s HTTP 200, returned document.", vars["doc_id"]))
fmt.Fprintln(w, ret)
}
func GetEndpointByCase(w http.ResponseWriter, r *http.Request) {
r.Header.Set("Content-Type", "application/json; charset=UTF-8")
var (
method, ret string
conf *config.ConfigVars
err error
client *elastic.Client
query elastic.Query
agg elastic.Aggregation
at *elastic.SearchResult
a *elastic.AggregationBucketKeyItems
i []ReturnBucket
found bool
)
vars := mux.Vars(r)
vars_case := vars["case"]
conf, err = config.ReadConfFile()
if err != nil {
api.LogError(api.DEBUG, err)
}
if conf.Elastic.Elastic_ssl {
method = api.HTTPS
} else {
method = api.HTTP
}
client, err = elastic.NewClient(elastic.SetURL(fmt.Sprintf("%s%s:%d", method, conf.Elastic.Elastic_server, conf.Elastic.Elastic_port)))
if err != nil {
api.LogError(api.DEBUG, err)
}
agg = elastic.NewTermsAggregation().
Field("ComputerName.keyword").
Size(50000)
query = elastic.NewBoolQuery().Must(elastic.NewTermQuery("CaseInfo.case_name.keyword", vars_case))
at, err = client.Search().
Index(conf.Elastic.Elastic_index).
Query(query).
Size(0).
Aggregation("endpoints", agg).
Do(context.Background())
if err != nil {
api.HttpFailureMessage(fmt.Sprintf("Elasticsearch Error: %s", err.Error()))
api.LogError(api.DEBUG, err)
return
}
a, found = at.Aggregations.Terms("endpoints")
if !found {
api.LogDebug(api.DEBUG, "[!] Aggregation not found!")
}
for _, v := range a.Buckets {
i = append(i, ReturnBucket{
Key: v.Key.(string),
DocCount: v.DocCount,
})
}
ret = api.HttpSuccessMessage("200", &i, at.TotalHits())
api.LogDebug(api.DEBUG, fmt.Sprintf("[+] GET /show/%s HTTP 200, returned endpoints list for case.", vars_case))
fmt.Fprintln(w, ret)
}
func GetCasedateByEndpoint(w http.ResponseWriter, r *http.Request) {
r.Header.Set("Content-Type", "application/json; charset=UTF-8")
var (
method, ret string
conf *config.ConfigVars
err error
client *elastic.Client
query elastic.Query
agg elastic.Aggregation
at *elastic.SearchResult
a *elastic.AggregationBucketKeyItems
i []CaseBucket
found bool
)
vars := mux.Vars(r)
vars_case := vars["case"]
vars_endpoint := vars["endpoint"]
conf, err = config.ReadConfFile()
if err != nil {
api.LogError(api.DEBUG, err)
}
if conf.Elastic.Elastic_ssl {
method = api.HTTPS
} else {
method = api.HTTP
}
client, err = elastic.NewClient(elastic.SetURL(fmt.Sprintf("%s%s:%d", method, conf.Elastic.Elastic_server, conf.Elastic.Elastic_port)))
if err != nil {
api.LogError(api.DEBUG, err)
}
agg = elastic.NewTermsAggregation().
Field("CaseInfo.case_date").
Size(500)
query = elastic.NewBoolQuery().Must(
elastic.NewTermQuery("CaseInfo.case_name.keyword", vars_case),
elastic.NewTermQuery("ComputerName.keyword", vars_endpoint))
at, err = client.Search().
Index(conf.Elastic.Elastic_index).
Query(query).
Size(0).
Aggregation("case_dates", agg).
Do(context.Background())
if err != nil {
api.HttpFailureMessage(fmt.Sprintf("Elasticsearch Error: %s", err.Error()))
api.LogError(api.DEBUG, err)
}
a, found = at.Aggregations.Terms("case_dates")
if !found {
api.LogDebug(api.DEBUG, "[!] Aggregation not found!")
}
for _, v := range a.Buckets {
i = append(i, CaseBucket{
KeyAsString: *v.KeyAsString,
DocCount: v.DocCount,
})
}
ret = api.HttpSuccessMessage("200", &i, at.TotalHits())
api.LogDebug(api.DEBUG, fmt.Sprintf("[+] GET /show/%s/%s HTTP 200, returned case dates for endpoint.", vars_case, vars_endpoint))
fmt.Fprintln(w, ret)
}
func GetAuditTypeByEndpointAndCase(w http.ResponseWriter, r *http.Request) {
r.Header.Set("Content-Type", "application/json; charset=UTF-8")
var (
method, ret string
client *elastic.Client
query elastic.Query
agg elastic.Aggregation
at *elastic.SearchResult
a *elastic.AggregationBucketKeyItems
i []ReturnBucket
found bool
)
vars := mux.Vars(r)
vars_case := vars["case"]
vars_endpoint := vars["endpoint"]
vars_case_date := vars["case_date"]
conf, err := config.ReadConfFile()
if err != nil {
api.LogError(api.DEBUG, err)
}
if conf.Elastic.Elastic_ssl {
method = api.HTTPS
} else {
method = api.HTTP
}
client, err = elastic.NewClient(elastic.SetURL(fmt.Sprintf("%s%s:%d", method, conf.Elastic.Elastic_server, conf.Elastic.Elastic_port)))
if err != nil {
api.LogError(api.DEBUG, err)
}
agg = elastic.NewTermsAggregation().
Field("AuditType.Generator.keyword").
Size(16)
query = elastic.NewBoolQuery().Must(
elastic.NewTermQuery("CaseInfo.case_name.keyword", vars_case),
elastic.NewTermQuery("ComputerName.keyword", vars_endpoint),
elastic.NewTermQuery("CaseInfo.case_date", vars_case_date))
at, err = client.Search().
Index(conf.Elastic.Elastic_index).
Query(query).
Size(0).
Aggregation("audits", agg).
Do(context.Background())
if err != nil {
api.HttpFailureMessage(fmt.Sprintf("Elasticsearch Error: %s", err.Error()))
api.LogError(api.DEBUG, err)
}
a, found = at.Aggregations.Terms("audits")
if !found {
api.LogDebug(api.DEBUG, "[!] Aggregation not found!")
}
for _, v := range a.Buckets {
i = append(i, ReturnBucket{
Key: v.Key.(string),
DocCount: v.DocCount,
})
}
ret = api.HttpSuccessMessage("200", &i, at.TotalHits())
api.LogDebug(api.DEBUG, fmt.Sprintf("[+] GET /show/%s/%s/%s HTTP 200, returned audit list for endpoint.", vars_case, vars_endpoint, vars_case_date))
fmt.Fprintln(w, ret)
}
func GetAuditDataByAuditGenerator(w http.ResponseWriter, r *http.Request) {
r.Header.Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
var (
from int
sort_field string
sort_order bool
method, ret string
client *elastic.Client
at *elastic.SearchResult
query elastic.Query
filter FilterOn
)
// Setting default value for sort_order
// and sort_field
sort_field = "Record.TlnTime" // default field to sort
sort_order = true // sort in ascending order
uriSortField := r.URL.Query().Get("sort")
if uriSortField != "" {
sort_field = uriSortField
}
uriSortOrder := r.URL.Query().Get("order")
// Values from RequestURI
vars_case := vars["case"]
vars_endpoint := vars["endpoint"]
vars_audittype := vars["audittype"]
vars_case_date := vars["case_date"]
switch uriSortOrder {
case "desc":
sort_order = true
break
case "asc":
sort_order = false
}
if f, err := strconv.Atoi(r.URL.Query().Get("from")); err == nil {
from = f
}
conf, err := config.ReadConfFile()
if err != nil {
api.LogError(api.DEBUG, err)
}
if conf.Elastic.Elastic_ssl {
method = api.HTTPS
} else {
method = api.HTTP
}
client, err = elastic.NewClient(elastic.SetURL(fmt.Sprintf("%s%s:%d", method, conf.Elastic.Elastic_server, conf.Elastic.Elastic_port)))
if err != nil {
api.LogError(api.DEBUG, err)
}
if r.Method == "POST" {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
api.LogDebug(api.DEBUG, "[+] POST /show/audit/filter, Error encountered")
fmt.Fprintln(w, api.HttpFailureMessage("Failed to read HTTP request"))
return
}
json.Unmarshal(body, &filter)
query = elastic.NewBoolQuery().Must(
elastic.NewTermQuery("CaseInfo.case_name.keyword", vars_case),
elastic.NewTermQuery("ComputerName.keyword", vars_endpoint),
elastic.NewTermQuery("AuditType.Generator.keyword", vars_audittype),
elastic.NewTermQuery("CaseInfo.case_date", vars_case_date),
elastic.NewWildcardQuery(filter.ColId, filter.Filter.FilterQuery.(string)))
} else {
query = elastic.NewBoolQuery().Must(
elastic.NewTermQuery("CaseInfo.case_name.keyword", vars_case),
elastic.NewTermQuery("ComputerName.keyword", vars_endpoint),
elastic.NewTermQuery("AuditType.Generator.keyword", vars_audittype),
elastic.NewTermQuery("CaseInfo.case_date", vars_case_date))
}
at, err = client.Search().
Index(conf.Elastic.Elastic_index).
Query(query).
Size(100).
Sort(sort_field, sort_order).
From(from).
Do(context.Background())
if err != nil {
api.HttpFailureMessage(fmt.Sprintf("Elasticsearch Error: %s", err.Error()))
api.LogError(api.DEBUG, errors.New(fmt.Sprintf("%s - %s", r.RequestURI, err.Error())))
return
}
ret = api.HttpSuccessMessage("200", &at.Hits.Hits, at.Hits.TotalHits)
api.LogDebug(api.DEBUG, fmt.Sprintf("[+] GET /show/%s/%s/%s/%s HTTP 200, returned audit data for endpoint/case", vars_case, vars_endpoint, vars_case_date, vars_audittype))
fmt.Fprintln(w, ret)
}
|
// Copyright © 2021 Attestant Limited.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package standard
import (
"context"
eth2client "github.com/attestantio/go-eth2-client"
"github.com/attestantio/vouch/services/accountmanager"
"github.com/attestantio/vouch/services/chaintime"
"github.com/attestantio/vouch/services/metrics"
nullmetrics "github.com/attestantio/vouch/services/metrics/null"
"github.com/attestantio/vouch/services/signer"
"github.com/attestantio/vouch/services/submitter"
"github.com/attestantio/vouch/services/synccommitteeaggregator"
"github.com/pkg/errors"
"github.com/rs/zerolog"
)
type parameters struct {
logLevel zerolog.Level
processConcurrency int64
monitor metrics.SyncCommitteeMessageMonitor
chainTimeService chaintime.Service
syncCommitteeAggregator synccommitteeaggregator.Service
specProvider eth2client.SpecProvider
beaconBlockRootProvider eth2client.BeaconBlockRootProvider
syncCommitteeMessagesSubmitter submitter.SyncCommitteeMessagesSubmitter
validatingAccountsProvider accountmanager.ValidatingAccountsProvider
syncCommitteeRootSigner signer.SyncCommitteeRootSigner
syncCommitteeSelectionSigner signer.SyncCommitteeSelectionSigner
syncCommitteeSubscriptionsSubmitter submitter.SyncCommitteeSubscriptionsSubmitter
}
// Parameter is the interface for service parameters.
type Parameter interface {
apply(*parameters)
}
type parameterFunc func(*parameters)
func (f parameterFunc) apply(p *parameters) {
f(p)
}
// WithLogLevel sets the log level for the module.
func WithLogLevel(logLevel zerolog.Level) Parameter {
return parameterFunc(func(p *parameters) {
p.logLevel = logLevel
})
}
// WithProcessConcurrency sets the concurrency for the service.
func WithProcessConcurrency(concurrency int64) Parameter {
return parameterFunc(func(p *parameters) {
p.processConcurrency = concurrency
})
}
// WithMonitor sets the monitor for this module.
func WithMonitor(monitor metrics.SyncCommitteeMessageMonitor) Parameter {
return parameterFunc(func(p *parameters) {
p.monitor = monitor
})
}
// WithChainTimeService sets the chaintime service.
func WithChainTimeService(service chaintime.Service) Parameter {
return parameterFunc(func(p *parameters) {
p.chainTimeService = service
})
}
// WithSyncCommitteeAggregator sets the sync committee aggregator.
func WithSyncCommitteeAggregator(aggregator synccommitteeaggregator.Service) Parameter {
return parameterFunc(func(p *parameters) {
p.syncCommitteeAggregator = aggregator
})
}
// WithSpecProvider sets the spec provider.
func WithSpecProvider(provider eth2client.SpecProvider) Parameter {
return parameterFunc(func(p *parameters) {
p.specProvider = provider
})
}
// WithBeaconBlockRootProvider sets the beacon block root provider.
func WithBeaconBlockRootProvider(provider eth2client.BeaconBlockRootProvider) Parameter {
return parameterFunc(func(p *parameters) {
p.beaconBlockRootProvider = provider
})
}
// WithSyncCommitteeMessagesSubmitter sets the sync committee messages submitter.
func WithSyncCommitteeMessagesSubmitter(submitter submitter.SyncCommitteeMessagesSubmitter) Parameter {
return parameterFunc(func(p *parameters) {
p.syncCommitteeMessagesSubmitter = submitter
})
}
// WithValidatingAccountsProvider sets the account manager.
func WithValidatingAccountsProvider(provider accountmanager.ValidatingAccountsProvider) Parameter {
return parameterFunc(func(p *parameters) {
p.validatingAccountsProvider = provider
})
}
// WithSyncCommitteeRootSigner sets the sync committee root signer.
func WithSyncCommitteeRootSigner(signer signer.SyncCommitteeRootSigner) Parameter {
return parameterFunc(func(p *parameters) {
p.syncCommitteeRootSigner = signer
})
}
// WithSyncCommitteeSelectionSigner sets the sync committee selection signer.
func WithSyncCommitteeSelectionSigner(signer signer.SyncCommitteeSelectionSigner) Parameter {
return parameterFunc(func(p *parameters) {
p.syncCommitteeSelectionSigner = signer
})
}
// WithSyncCommitteeSubscriptionsSubmitter sets the sync committee subscriptions submitter.
func WithSyncCommitteeSubscriptionsSubmitter(submitter submitter.SyncCommitteeSubscriptionsSubmitter) Parameter {
return parameterFunc(func(p *parameters) {
p.syncCommitteeSubscriptionsSubmitter = submitter
})
}
// parseAndCheckParameters parses and checks parameters to ensure that mandatory parameters are present and correct.
func parseAndCheckParameters(params ...Parameter) (*parameters, error) {
parameters := parameters{
logLevel: zerolog.GlobalLevel(),
monitor: nullmetrics.New(context.Background()),
}
for _, p := range params {
if params != nil {
p.apply(¶meters)
}
}
if parameters.processConcurrency < 1 {
return nil, errors.New("no process concurrency specified")
}
if parameters.monitor == nil {
return nil, errors.New("no monitor specified")
}
if parameters.specProvider == nil {
return nil, errors.New("no spec provider specified")
}
if parameters.chainTimeService == nil {
return nil, errors.New("no chain time service specified")
}
if parameters.syncCommitteeAggregator == nil {
return nil, errors.New("no sync committee aggregator specified")
}
if parameters.beaconBlockRootProvider == nil {
return nil, errors.New("no beacon block root provider specified")
}
if parameters.syncCommitteeMessagesSubmitter == nil {
return nil, errors.New("no sync committee messages submitter specified")
}
if parameters.syncCommitteeSubscriptionsSubmitter == nil {
return nil, errors.New("no sync committee subscriptions submitter specified")
}
if parameters.validatingAccountsProvider == nil {
return nil, errors.New("no validating accounts provider specified")
}
if parameters.syncCommitteeSelectionSigner == nil {
return nil, errors.New("no sync committee selection signer specified")
}
if parameters.syncCommitteeRootSigner == nil {
return nil, errors.New("no sync committee root signer specified")
}
return ¶meters, nil
}
|
package cointop
import (
"log"
"os/exec"
"github.com/jroimartin/gocui"
)
func (ct *Cointop) setKeybinding(key interface{}, callback func(g *gocui.Gui, v *gocui.View) error) {
var err error
switch t := key.(type) {
case gocui.Key:
err = ct.g.SetKeybinding("", t, gocui.ModNone, callback)
case rune:
err = ct.g.SetKeybinding("", t, gocui.ModNone, callback)
}
if err != nil {
log.Fatal(err)
}
}
func (ct *Cointop) keybindings(g *gocui.Gui) error {
ct.setKeybinding(gocui.KeyArrowRight, ct.nextPage)
ct.setKeybinding(gocui.KeyCtrlN, ct.nextPage)
ct.setKeybinding(gocui.KeyArrowLeft, ct.prevPage)
ct.setKeybinding(gocui.KeyCtrlP, ct.prevPage)
ct.setKeybinding(gocui.KeyArrowDown, ct.cursorDown)
ct.setKeybinding('j', ct.cursorDown)
ct.setKeybinding(gocui.KeyArrowUp, ct.cursorUp)
ct.setKeybinding('k', ct.cursorUp)
ct.setKeybinding(gocui.KeyCtrlD, ct.pageDown)
ct.setKeybinding(gocui.KeyCtrlU, ct.pageUp)
ct.setKeybinding('r', ct.sortfn("rank", false))
ct.setKeybinding('n', ct.sortfn("name", true))
ct.setKeybinding('s', ct.sortfn("symbol", false))
ct.setKeybinding('p', ct.sortfn("price", true))
ct.setKeybinding('m', ct.sortfn("marketcap", true))
ct.setKeybinding('v', ct.sortfn("24hvolume", true))
ct.setKeybinding('1', ct.sortfn("1hchange", true))
ct.setKeybinding('2', ct.sortfn("24hchange", true))
ct.setKeybinding('7', ct.sortfn("7dchange", true))
ct.setKeybinding('t', ct.sortfn("totalsupply", true))
ct.setKeybinding('a', ct.sortfn("availablesupply", true))
ct.setKeybinding('l', ct.sortfn("lastupdated", true))
ct.setKeybinding(gocui.KeyCtrlR, ct.refresh)
ct.setKeybinding(gocui.KeyEnter, ct.enter)
ct.setKeybinding(gocui.KeySpace, ct.enter)
ct.setKeybinding(gocui.KeyCtrlC, ct.quit)
ct.setKeybinding('q', ct.quit)
ct.setKeybinding(gocui.KeyEsc, ct.quit)
return nil
}
func (ct *Cointop) refresh(g *gocui.Gui, v *gocui.View) error {
ct.forcerefresh <- true
return nil
}
func (ct *Cointop) enter(g *gocui.Gui, v *gocui.View) error {
exec.Command("open", ct.rowLink()).Output()
return nil
}
func (ct *Cointop) quit(g *gocui.Gui, v *gocui.View) error {
return gocui.ErrQuit
}
|
package memory
import (
"context"
"errors"
"go.uber.org/zap"
"github.com/silverspase/todo/internal/modules/todo"
"github.com/silverspase/todo/internal/modules/todo/model"
)
type memoryStorage struct {
items map[string]model.Item // TODO change to sync.Map
// itemsArray []model.Item // TODO use this for pagination in GetAllItems
logger *zap.Logger
}
func NewMemoryStorage(logger *zap.Logger) todo.Repository {
return &memoryStorage{
items: make(map[string]model.Item),
logger: logger,
}
}
func (m memoryStorage) CreateItem(ctx context.Context, item model.Item) (string, error) {
m.logger.Debug("CreateItem")
m.items[item.ID] = item
return item.ID, nil
}
func (m memoryStorage) GetAllItems(ctx context.Context, page int) (res []model.Item, err error) {
for _, item := range m.items {
res = append(res, item)
}
return res, nil
}
func (m memoryStorage) GetItem(ctx context.Context, id string) (model.Item, error) {
m.logger.Debug("GetItem")
item, ok := m.items[id]
if !ok {
return item, errors.New("not found")
}
return item, nil
}
func (m memoryStorage) UpdateItem(ctx context.Context, item model.Item) (string, error) {
_, ok := m.items[item.ID]
if !ok {
return "", errors.New("item with given id not found, nothing to update")
}
m.items[item.ID] = item
return item.ID, nil
}
func (m memoryStorage) DeleteItem(ctx context.Context, id string) (string, error) {
_, ok := m.items[id]
if !ok {
return "", errors.New("item with given id not found, nothing to delete")
}
delete(m.items, id)
return id, nil
}
|
package component
import "image/color"
// Rect component.
type Rect struct {
Color color.RGBA
W, H int32
Active bool
}
// NewRect rect constructor.
func NewRect(c color.RGBA, w, h int32, active bool) *Rect {
return &Rect{c, w, h, active}
}
// Name component implementation.
func (c *Rect) Name() string {
return "rect"
}
|
package db
import (
"os"
"github.com/sirupsen/logrus"
"gitlab.com/NagByte/Palette/common"
"gitlab.com/NagByte/Palette/db/mongo"
"gitlab.com/NagByte/Palette/db/neo4j"
"gitlab.com/NagByte/Palette/db/wrapper"
)
var (
Neo wrapper.Database
Mongo wrapper.Database
)
func init() {
mongoInit()
neoInit()
}
func neoInit() {
log := logrus.WithField("WHERE", "db.neo4j.neoinit")
var err error
neoURI := common.ConfigString("NEO_URI")
if neoURI == "" {
log.Errorln("Variable NEO_URI not presented.")
os.Exit(1)
}
log.Infof("Connecting Neo4J on %s...\n", neoURI)
Neo, err = neo4j.New(neoURI, 25)
if err != nil {
log.Panicln("Can not connect to Neo4j: ", err.Error())
}
Neo.Init()
}
func mongoInit() {
log := logrus.WithField("WHERE", "[db.neo4j.mongoInit()]")
var err error
mongoURI := common.ConfigString("MONGO_URI")
if mongoURI == "" {
log.Errorln("Variable MONGO_URI not presented.")
os.Exit(1)
}
log.Infof("Connecting Mongo on %s...\n", mongoURI)
Mongo, err = mongo.New(mongoURI, "palette")
if err != nil {
log.Panicln("Can not connect to MongoDB: ", err.Error())
}
Mongo.Init()
common.AddMongoHooker(mongoURI, "palette", "log")
}
|
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//go:build ignore
// +build ignore
package main
import (
"crypto/tls"
"log"
"net"
"net/http"
"time"
"github.com/elastic/go-elasticsearch/v8"
)
func main() {
log.SetFlags(0)
// This example demonstrates how to configure the client's Transport.
//
// NOTE: These values are for illustrative purposes only, and not suitable
// for any production use. The default transport is sufficient.
//
cfg := elasticsearch.Config{
Addresses: []string{"http://localhost:9200"},
Transport: &http.Transport{
MaxIdleConnsPerHost: 10,
ResponseHeaderTimeout: time.Millisecond,
DialContext: (&net.Dialer{Timeout: time.Nanosecond}).DialContext,
TLSClientConfig: &tls.Config{
MinVersion: tls.VersionTLS12,
// ...
},
},
}
es, err := elasticsearch.NewClient(cfg)
if err != nil {
log.Printf("Error creating the client: %s", err)
} else {
log.Println(es.Info())
// => dial tcp: i/o timeout
}
}
|
package Models
type Client struct {
Id uint `json:"id"`
Name string `json:"name"`
URL string `json:"url"`
Description string `json:"description"`
}
func (c *Client) TableName() string {
return "client"
} |
package main
import (
"context"
"log"
pb "github.com/naichadouban/learngrpc/demo7-simple-http/proto"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"net"
"time"
)
const (
port = ":8010"
)
type Auth struct {
appKey string
appSecret string
}
func (a *Auth) GetAppKey() string {
return "testname"
}
func (a *Auth) GetAppSecret() string {
return "testpass"
}
func (a *Auth) Check(ctx context.Context) error {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return status.Errorf(codes.Unauthenticated, "自定义认证 Token 失败")
}
var (
appKey string
appSecret string
)
if value, ok := md["app_key"]; ok {
appKey = value[0]
}
if value, ok := md["app_secret"]; ok {
appSecret = value[0]
}
if appKey != a.GetAppKey() || appSecret != a.GetAppSecret() {
return status.Errorf(codes.Unauthenticated, "自定义认证 Token 无效")
}
return nil
}
type SearchService struct {
auth *Auth
}
func (s *SearchService) Search(ctx context.Context, r *pb.SearchRequest) (*pb.SearchResponse, error) {
// 这是自定义的认证
if err := s.auth.Check(ctx); err != nil {
return nil, err
}
for i := 0; i < 3; i++ {
// 而在 Server 端,由于 Client 已经设置了截止时间。Server 势必要去检测它
// 否则如果 Client 已经结束掉了,Server 还傻傻的在那执行,这对资源是一种极大的浪费
if ctx.Err() == context.Canceled {
return nil, status.Errorf(codes.Canceled, "SearchService.Search canceled")
}
time.Sleep(1 * time.Second)
log.Printf("time:%d\n", i)
}
return &pb.SearchResponse{Response: r.GetRequest() + "server"}, nil
}
func main() {
certFile := "./conf/server/server.crt"
keyFile := "./conf/server/server.key"
c, err := credentials.NewServerTLSFromFile(certFile, keyFile)
if err != nil {
log.Panicln(err)
}
server := grpc.NewServer(grpc.Creds(c))
pb.RegisterSearchServiceServer(server, &SearchService{})
lis, err := net.Listen("tcp", port)
if err != nil {
log.Println(err)
}
err = server.Serve(lis)
log.Println(err)
}
|
package app
import (
"errors"
"strings"
"testing"
"github.com/10gen/realm-cli/internal/cli"
"github.com/10gen/realm-cli/internal/cloud/realm"
"github.com/10gen/realm-cli/internal/utils/test/assert"
"github.com/10gen/realm-cli/internal/utils/test/mock"
"go.mongodb.org/mongo-driver/bson/primitive"
)
func TestAppDeleteHandler(t *testing.T) {
groupID1 := primitive.NewObjectID().Hex()
groupID2 := primitive.NewObjectID().Hex()
appID1 := "60344735b37e3733de2adf40"
appID2 := "60344735b37e3733de2adf41"
appID3 := "60344735b37e3733de2adf42"
app1 := realm.App{
ID: appID1,
GroupID: groupID1,
ClientAppID: "app1-abcde",
Name: "app1",
}
app2 := realm.App{
ID: appID2,
GroupID: groupID2,
ClientAppID: "app2-defgh",
Name: "app2",
}
app3 := realm.App{
ID: appID3,
GroupID: groupID1,
ClientAppID: "app2-hijkl",
Name: "app2",
}
for _, tc := range []struct {
description string
inputs deleteInputs
apps []realm.App
deleteErr error
expectedApps []string
expectedOutput string
}{
{
description: "should delete no apps if none are found",
expectedOutput: "No apps to delete\n",
},
{
description: "with no project flag set and an apps flag set should delete all apps that match the apps flag",
inputs: deleteInputs{Apps: []string{"app1"}},
apps: []realm.App{app1, app2, app3},
expectedApps: []string{appID1},
expectedOutput: strings.Join(
[]string{
"Successfully deleted 1/1 app(s)",
" ID Name Deleted Details",
" ------------------------ ---- ------- -------",
" 60344735b37e3733de2adf40 app1 true ",
"",
},
"\n",
),
},
{
description: "with a project flag set and an apps flag set should delete all apps that match the apps flag",
inputs: deleteInputs{Apps: []string{"app1", "app2"}, Project: groupID1},
apps: []realm.App{app1, app2, app3},
expectedApps: []string{appID1, appID3},
expectedOutput: strings.Join(
[]string{
"Successfully deleted 2/2 app(s)",
" ID Name Deleted Details",
" ------------------------ ---- ------- -------",
" 60344735b37e3733de2adf40 app1 true ",
" 60344735b37e3733de2adf42 app2 true ",
"",
},
"\n",
),
},
{
description: "should indicate an error if deleting an app fails",
inputs: deleteInputs{Apps: []string{"app1"}, Project: groupID1},
apps: []realm.App{app1},
expectedApps: []string{},
deleteErr: errors.New("client error"),
expectedOutput: strings.Join(
[]string{
"Successfully deleted 0/1 app(s)",
" ID Name Deleted Details ",
" ------------------------ ---- ------- ------------",
" 60344735b37e3733de2adf40 app1 false client error",
"",
},
"\n",
),
},
} {
t.Run(tc.description, func(t *testing.T) {
out, ui := mock.NewUI()
realmClient := mock.RealmClient{}
var capturedFindGroupID string
realmClient.FindAppsFn = func(filter realm.AppFilter) ([]realm.App, error) {
capturedFindGroupID = filter.GroupID
return tc.apps, nil
}
var capturedApps = make([]string, 0)
realmClient.DeleteAppFn = func(groupID, appID string) error {
capturedApps = append(capturedApps, appID)
return tc.deleteErr
}
cmd := &CommandDelete{inputs: tc.inputs}
assert.Nil(t, cmd.Handler(nil, ui, cli.Clients{Realm: realmClient}))
assert.Equal(t, tc.expectedOutput, out.String())
assert.Equal(t, tc.inputs.Project, capturedFindGroupID)
})
}
}
|
package main
import (
"fmt"
)
func main() {
for i := 0; i < 1; i++ {
switch {
case true:
fmt.Println("hello")
break // target is switch
}
fmt.Println("world") // reachable
}
fmt.Println("----- use label -----")
FOR:
for i := 0; i < 1; i++ {
switch {
case true:
fmt.Println("hello")
break FOR // target is FOR:
}
fmt.Println("world") // unreachable
}
}
|
package core
import (
"encoding/hex"
"fmt"
"github.com/golang/protobuf/ptypes"
"github.com/mr-tron/base58/base58"
"github.com/textileio/go-textile/crypto"
"github.com/textileio/go-textile/pb"
"golang.org/x/crypto/bcrypt"
)
// CafeTokens lists all locally-stored (bcrypt hashed) tokens
func (t *Textile) CafeTokens() ([]string, error) {
tokens := t.datastore.CafeTokens().List()
strings := make([]string, len(tokens))
for i, token := range tokens {
id, err := hex.DecodeString(token.Id)
if err != nil {
return []string{}, err
}
strings[i] = base58.FastBase58Encoding(append(id, token.Value...))
}
return strings, nil
}
// CreateCafeToken creates (or uses `token`) random access token, returns base58 encoded version,
// and stores (unless `store` is false) a bcrypt hashed version for later comparison
func (t *Textile) CreateCafeToken(token string, store bool) (string, error) {
var key []byte
var err error
if token != "" {
key, err = base58.FastBase58Decoding(token)
if err != nil {
return "", err
}
if len(key) != 44 {
return "", fmt.Errorf("invalid token format")
}
} else {
key, err = crypto.GenerateAESKey()
if err != nil {
return "", err
}
}
rawToken := key[12:]
safeToken, err := bcrypt.GenerateFromPassword(rawToken, bcrypt.DefaultCost)
if err != nil {
return "", err
}
if store {
if err := t.datastore.CafeTokens().Add(&pb.CafeToken{
Id: hex.EncodeToString(key[:12]),
Value: safeToken,
Date: ptypes.TimestampNow(),
}); err != nil {
return "", err
}
}
return base58.FastBase58Encoding(key), nil
}
// ValidateCafeToken checks whether a supplied base58 encoded token matches the locally-stored
// bcrypt hashed equivalent
func (t *Textile) ValidateCafeToken(token string) (bool, error) {
// dev tokens are actually base58(id+token)
plainBytes, err := base58.FastBase58Decoding(token)
if err != nil {
return false, err
}
if len(plainBytes) < 44 {
return false, fmt.Errorf("invalid token format")
}
encodedToken := t.datastore.CafeTokens().Get(hex.EncodeToString(plainBytes[:12]))
if encodedToken == nil {
return false, err
}
if err := bcrypt.CompareHashAndPassword(encodedToken.Value, plainBytes[12:]); err != nil {
return false, err
}
return true, nil
}
// RemoveCafeToken removes a given cafe token from the local store
func (t *Textile) RemoveCafeToken(token string) error {
// dev tokens are actually base58(id+token)
plainBytes, err := base58.FastBase58Decoding(token)
if err != nil {
return err
}
if len(plainBytes) < 44 {
return fmt.Errorf("invalid token format")
}
return t.datastore.CafeTokens().Delete(hex.EncodeToString(plainBytes[:12]))
}
|
package filepath
import "strings"
// Join is an explicit-OS version of path/filepath's Join.
func Join(os string, elem ...string) string {
sep := Separator(os)
return Clean(os, strings.Join(elem, string(sep)))
}
|
package endpoints
import (
"github.com/aws/aws-sdk-go/service/ec2"
)
type Clients struct {
EC2 EC2Client
}
// EC2Client describes the methods required to be implemented by a EC2 AWS client.
type EC2Client interface {
DescribeInstances(*ec2.DescribeInstancesInput) (*ec2.DescribeInstancesOutput, error)
}
|
package testapplication
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
)
// NewHandler returns a handler for "testapplication" type messages.
func NewHandler(keeper Keeper) sdk.Handler{
return func(ctx sdk.Context, msg sdk.Msg) sdk.Result{
switch msg := msg.(type){
case MsgTransmitBol:
return handleMsgTransmitBol(ctx, keeper, msg)
case MsgCreateBol:
return handleMsgCreateBol(ctx,keeper,msg)
case MsgSendMoney:
return handleMsgSendMoney(ctx, keeper,msg)
default:
errMsg := fmt.Sprintf("Unrecognized testapplication Msg type: %v", msg.Type())
return sdk.ErrUnknownRequest(errMsg).Result()
}
}
}
// func for the MsgTransmitBol
func handleMsgTransmitBol(ctx sdk.Context, keeper Keeper, msg MsgTransmitBol) sdk.Result {
if !msg.Owner.Equals(keeper.GetOwner(ctx, msg.Hash)) { // Checks if the the msg sender is the same as the current owner
return sdk.ErrUnauthorized("Incorrect Owner").Result() // If not, throw an error
}
keeper.SetOwner(ctx, msg.Hash, msg.NewOwner) // If so, set the owner to the newOwner specified in the msg.
return sdk.Result{} // return
}
func handleMsgCreateBol(ctx sdk.Context, keeper Keeper, msg MsgCreateBol) sdk.Result {
bol := NewBol(msg.Owner, msg.Hash)
keeper.SetBol(ctx,msg.Hash,bol)
return sdk.Result{}
}
//func for MsgSendMoney
func handleMsgSendMoney(ctx sdk.Context, keeper Keeper, msg MsgSendMoney) sdk.Result {
_, err := keeper.coinKeeper.SendCoins(ctx, msg.Sender, msg.Destination, msg.Amount)
if err != nil {
return sdk.ErrInsufficientCoins("Buyer does not have enough coins").Result()
}
/*_, err = k.coinKeeper.SubtractCoins(ctx, msg.Sender, msg.Amount)
if err != nil {
return sdk.ErrInsufficientCoins("Buyer does not have enough coins").Result()
}*/
return sdk.Result{}
}
|
package main
import (
"net/http"
"html/template"
"io"
)
var t *template.Template
func init(){
t=template.Must(template.ParseFiles("112_ajaxserver2.html"))
}
func main() {
http.HandleFunc("/",index)
http.HandleFunc("/foo",foo)
http.Handle("/favicon.ico",http.NotFoundHandler())
http.ListenAndServe(":8080",nil)
}
func index(w http.ResponseWriter,r *http.Request){
t.ExecuteTemplate(w,"112_ajaxserver2.html",nil)
}
func foo(w http.ResponseWriter,r *http.Request){
io.WriteString(w,"my foo page !")
} |
/*
* randmat: random number generation
*
* input:
* nrows, ncols: the number of rows and columns
* s: the seed
*
* output:
* Randmat_matrix: a nrows x ncols integer matrix
*
*/
package all
var Randmat_matrix [][]byte;
func randvec(row, n, seed int, done chan bool) {
LCG_A := uint32(1664525)
LCG_C := uint32(1013904223)
s := uint32(seed)
for j := 0; j < n; j++ {
s = LCG_A*s + LCG_C
Randmat_matrix[row][j] = byte(s % 100)
}
done <- true
}
func parallel_for(begin, end, ncols, s int, done chan bool) {
if (begin + 1 == end) {
randvec(begin, ncols, s + begin, done);
} else {
middle := begin + (end - begin) / 2;
go parallel_for(begin, middle, ncols, s, done);
parallel_for(middle, end, ncols, s, done);
}
}
func Randmat(nrows, ncols, s int) {
Randmat_matrix = make ([][]byte, nrows)
for i := range Randmat_matrix {
Randmat_matrix [i] = make ([]byte, ncols)
}
done := make(chan bool);
// parallel for on rows
go parallel_for(0, nrows, ncols, s, done);
for i := 0; i < nrows; i++ {
<-done;
}
}
|
package flag
import (
"testing"
rzcheck "github.com/robert-zaremba/checkers"
gocheck "gopkg.in/check.v1"
)
// Hook up gocheck into the "go test" runner.
func Test(t *testing.T) { gocheck.TestingT(t) }
type ExtraSuite struct{}
func init() {
gocheck.Suite(&ExtraSuite{})
}
func (s *ExtraSuite) TestValidateDirExists(c *gocheck.C) {
ff := Path{}
err := ff.Set("/tmp")
c.Assert(err, gocheck.IsNil)
c.Assert(ff.String(), gocheck.Equals, "/tmp")
}
func (s *ExtraSuite) TestValidatePermissionDenied(c *gocheck.C) {
ff := Path{}
_ = ff.Set("/root/secret")
err := ff.Check()
c.Assert(err, gocheck.ErrorMatches, "stat /root/secret: permission denied")
}
func (s *ExtraSuite) TestValidateNoFile(c *gocheck.C) {
ff := Path{}
_ = ff.Set("")
err := ff.Check()
c.Assert(err, rzcheck.ErrorContains, "File path can't be empty")
}
func (s *ExtraSuite) TestHandleBadDefaultWithPanic(c *gocheck.C) {
ff := Path{"hello-world"}
err := ff.Check()
c.Assert(err, gocheck.ErrorMatches, "stat hello-world: no such file or directory")
}
func (s *ExtraSuite) TestHandleDefault(c *gocheck.C) {
ff := Path{"/tmp"}
c.Assert(ff.String(), gocheck.Equals, "/tmp")
ff = Path{"/"}
c.Assert(ff.String(), gocheck.Equals, "/")
err := ff.Set("/tmp")
c.Assert(err, gocheck.IsNil)
c.Assert(ff.String(), gocheck.Equals, "/tmp")
}
|
package calendar
import (
"context"
"github.com/Azimkhan/go-calendar-grpc/internal/models"
)
type Usecase interface {
Fetch(ctx context.Context) ([]*models.CalendarEvent, error)
GetByID(ctx context.Context, id int64) (*models.CalendarEvent, error)
Update(ctx context.Context, ar *models.CalendarEvent) error
Store(context.Context, *models.CalendarEvent) error
Delete(ctx context.Context, id int64) error
}
|
package request
import "github.com/dmitrymomot/go-jwt"
type (
// Auth interface
Auth interface {
GetAccessToken() string
GetUserID() string
SetUserID(uid string)
GetUserRole() string
SetUserRole(role string)
GetAppID() string
SetAppID(aid string)
GetClaims() jwt.Claims
SetClaims(claims jwt.Claims)
}
// AuthArgs struct
AuthArgs struct {
AccessToken string `json:"__access_token"`
userID string
userRole string
appID string
claims jwt.Claims
}
)
// GetAccessToken ...
func (a *AuthArgs) GetAccessToken() string {
return a.AccessToken
}
// GetUserID ...
func (a *AuthArgs) GetUserID() string {
return a.userID
}
// SetUserID ...
func (a *AuthArgs) SetUserID(uid string) {
a.userID = uid
}
// GetUserRole ...
func (a *AuthArgs) GetUserRole() string {
return a.userRole
}
// SetUserRole ...
func (a *AuthArgs) SetUserRole(role string) {
a.userRole = role
}
// GetAppID ...
func (a *AuthArgs) GetAppID() string {
return a.appID
}
// SetAppID ...
func (a *AuthArgs) SetAppID(aid string) {
a.appID = aid
}
// GetClaims ...
func (a *AuthArgs) GetClaims() jwt.Claims {
return a.claims
}
// SetClaims ...
func (a *AuthArgs) SetClaims(claims jwt.Claims) {
a.claims = claims
}
|
package main
type person struct {
name string
username string
age int
}
func (r *person) isFirst() {
r.username = "Qaroev"
r.name = "Gulboy"
r.age = 22
}
func main() {
ma1()
}
func (r *person) ma1() {
r.isFirst()
} |
package routers
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/context/param"
)
func init() {
beego.GlobalControllerRouter["sdrms/controllers:CategoryTypeController"] = append(beego.GlobalControllerRouter["sdrms/controllers:CategoryTypeController"],
beego.ControllerComments{
Method: "Index",
Router: `/`,
AllowHTTPMethods: []string{"get"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["sdrms/controllers:CategoryTypeController"] = append(beego.GlobalControllerRouter["sdrms/controllers:CategoryTypeController"],
beego.ControllerComments{
Method: "Delete",
Router: `/delete`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["sdrms/controllers:CategoryTypeController"] = append(beego.GlobalControllerRouter["sdrms/controllers:CategoryTypeController"],
beego.ControllerComments{
Method: "Edit",
Router: `/edit/?:id`,
AllowHTTPMethods: []string{"get","post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["sdrms/controllers:CategoryTypeController"] = append(beego.GlobalControllerRouter["sdrms/controllers:CategoryTypeController"],
beego.ControllerComments{
Method: "DataGrid",
Router: `/list`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["sdrms/controllers:ConfigGroupController"] = append(beego.GlobalControllerRouter["sdrms/controllers:ConfigGroupController"],
beego.ControllerComments{
Method: "Index",
Router: `/`,
AllowHTTPMethods: []string{"get"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["sdrms/controllers:ConfigGroupController"] = append(beego.GlobalControllerRouter["sdrms/controllers:ConfigGroupController"],
beego.ControllerComments{
Method: "Delete",
Router: `/delete`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["sdrms/controllers:ConfigGroupController"] = append(beego.GlobalControllerRouter["sdrms/controllers:ConfigGroupController"],
beego.ControllerComments{
Method: "Edit",
Router: `/edit/?:id`,
AllowHTTPMethods: []string{"get","post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["sdrms/controllers:ConfigGroupController"] = append(beego.GlobalControllerRouter["sdrms/controllers:ConfigGroupController"],
beego.ControllerComments{
Method: "DataGrid",
Router: `/list`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["sdrms/controllers:SystemConfigController"] = append(beego.GlobalControllerRouter["sdrms/controllers:SystemConfigController"],
beego.ControllerComments{
Method: "Index",
Router: `/`,
AllowHTTPMethods: []string{"get"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["sdrms/controllers:SystemConfigController"] = append(beego.GlobalControllerRouter["sdrms/controllers:SystemConfigController"],
beego.ControllerComments{
Method: "Config",
Router: `/Config/?:id`,
AllowHTTPMethods: []string{"get","post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["sdrms/controllers:SystemConfigController"] = append(beego.GlobalControllerRouter["sdrms/controllers:SystemConfigController"],
beego.ControllerComments{
Method: "DataList",
Router: `/DataList`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["sdrms/controllers:SystemConfigController"] = append(beego.GlobalControllerRouter["sdrms/controllers:SystemConfigController"],
beego.ControllerComments{
Method: "Delete",
Router: `/delete`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["sdrms/controllers:SystemConfigController"] = append(beego.GlobalControllerRouter["sdrms/controllers:SystemConfigController"],
beego.ControllerComments{
Method: "Edit",
Router: `/edit/?:id`,
AllowHTTPMethods: []string{"get","post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["sdrms/controllers:SystemConfigController"] = append(beego.GlobalControllerRouter["sdrms/controllers:SystemConfigController"],
beego.ControllerComments{
Method: "DataGrid",
Router: `/list`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["sdrms/controllers:SystemLoginLogController"] = append(beego.GlobalControllerRouter["sdrms/controllers:SystemLoginLogController"],
beego.ControllerComments{
Method: "Index",
Router: `/`,
AllowHTTPMethods: []string{"get"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["sdrms/controllers:SystemLoginLogController"] = append(beego.GlobalControllerRouter["sdrms/controllers:SystemLoginLogController"],
beego.ControllerComments{
Method: "DataGrid",
Router: `/DataGrid`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
}
|
package services
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"github.com/constant-money/constant-event/config"
)
// HookService : struct
type HookService struct{}
// Event : send data to logic server
func (h HookService) Event(jsonData map[string]interface{}) error {
conf := config.GetConfig()
endpoint := conf.HookEndpoint
endpoint = fmt.Sprintf("%s", endpoint)
jsonValue, _ := json.Marshal(jsonData)
request, _ := http.NewRequest("POST", endpoint, bytes.NewBuffer(jsonValue))
request.Header.Set("Content-Type", "application/json")
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
log.Println(err.Error())
return err
}
b, _ := ioutil.ReadAll(response.Body)
var data map[string]interface{}
json.Unmarshal(b, &data)
e := data["Error"]
if e == nil {
return nil
}
return errors.New(e.(string))
}
|
package main
import (
"io/ioutil"
"os"
"tibiaScrapper/bazaar"
"tibiaScrapper/utils"
"time"
"github.com/gocolly/colly/v2"
log "github.com/sirupsen/logrus"
)
type character struct {
Url string `json:"url"`
Name string `json:"char_name"`
CrawledAt time.Time `json:"crawled_at"`
}
type page struct {
Link string
Index string
}
func main() {
log.SetFormatter(&log.JSONFormatter{})
log.SetOutput(os.Stdout)
const baseUrl = "https://www.tibia.com/charactertrade/?subtopic=currentcharactertrades"
var c = colly.NewCollector()
var (
pages []page
characters []character
visitedPagesIndex = []string{"1"}
)
c.OnRequest(func(r *colly.Request) {
r.Headers.Set("User-Agent", utils.RandomString())
log.Infoln("Accessing: ", r.URL)
})
c.OnResponse(func(response *colly.Response) {
log.Infoln("Visited: ", response.Request.URL)
pages = append(
pages,
page{ Link: baseUrl, Index: "1"},
)
})
// Find Character Details
c.OnHTML(".Auction", func(e *colly.HTMLElement) {
charDetailsDOM := e.DOM.Find("div.AuctionCharacterName > a")
if bazaar.HasAlumni(e) {
charUrl, _ := charDetailsDOM.Attr("href")
charName := charDetailsDOM.Text()
log.WithFields(log.Fields{
"url": charUrl,
"name": charName,
}).Warnln("Character with Alumni achievement found!!")
characters = append(characters, character{
charUrl,
charName,
time.Now(),
})
}
})
c.OnHTML(".PageNavigation span.PageLink a[href]", func(e *colly.HTMLElement) {
link := e.Attr("href")
pageIndex := e.Text
//Avoid shortcuts to Last Page and First Page to follow natural path
if pageIndex == "Last Page" || pageIndex == "First Page" {
return
}
// If we already visited the page we can skip
if utils.InArray(visitedPagesIndex, pageIndex) {
return
}
visitedPagesIndex = append(visitedPagesIndex, pageIndex)
// Wait to don't get banned
utils.SleepRandom(3, 1)
//Access the next page
visitUrl(c, e.Request.AbsoluteURL(link))
})
visitUrl(c, baseUrl)
results, err := utils.ToJson(characters)
utils.HandleErrorDefault(err)
err = ioutil.WriteFile("outputs/"+ utils.GetFileNameWithTime("bazaar", ".json"), results, 0644)
utils.HandleErrorDefault(err)
}
func visitUrl(c *colly.Collector, url string) {
err := c.Visit(url)
utils.HandleErrorDefault(err)
}
|
package supl
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document01700101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:supl.017.001.01 Document"`
Message *PaymentSD1V01 `xml:"PmtSD1"`
}
func (d *Document01700101) AddMessage() *PaymentSD1V01 {
d.Message = new(PaymentSD1V01)
return d.Message
}
// Supplementary data for payment message definitions.
type PaymentSD1V01 struct {
// Structured card remittance information supplied in a payment.
CardRemittanceInformation *iso20022.TransactionData1 `xml:"CardRmtInf"`
}
func (p *PaymentSD1V01) AddCardRemittanceInformation() *iso20022.TransactionData1 {
p.CardRemittanceInformation = new(iso20022.TransactionData1)
return p.CardRemittanceInformation
}
|
package main
import (
"fmt"
"time"
"testing"
"sync"
)
// Messing with goroutines
func prnt(s string) {
fmt.Printf("[%s]\t\t%s\n", time.Now().String(), s)
}
func main() {
prnt("tests")
}
func Test1(t *testing.T) {
prnt("Test1 start")
go gotest()
time.Sleep(time.Millisecond * 10)
prnt("Test1 end")
}
func gotest() {
prnt("test groutine")
}
var lock sync.Mutex
func Test2(t *testing.T) {
prnt("Test2 start")
counter := 0
for i:=0; i<10; i++ {
go gotest2(&counter)
time.Sleep(time.Millisecond*10) //remove sleep and you get random outcome (1,1,1,1,1,2,2,2,3,3,...)
fmt.Printf("%d...", counter)
}
prnt("Test2 end")
}
func gotest2(counter *int) {
lock.Lock() //if you lock this goroutine, other increments don't do anything (1,1,1,1,1,1,1,1,1,...)
defer lock.Unlock()
*counter ++
}
|
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"os"
"github.com/doza-daniel/diameter/convexhull"
"github.com/doza-daniel/diameter/line"
"github.com/doza-daniel/diameter/point"
)
func main() {
flag.String("json", "", "JSON array of points")
flag.Parse()
file := flag.Arg(0)
var in *os.File
if file == "" || file == "-" {
in = os.Stdin
} else {
var err error
if in, err = os.Open(file); err != nil {
log.Fatal(err)
}
}
defer in.Close()
var points []point.Point
if err := json.NewDecoder(in).Decode(&points); err != nil {
log.Fatal(err)
}
p1, p2 := diameter(points)
fmt.Printf("Two most distant points: %s and %s\n", p1, p2)
}
func diameter(points []point.Point) (point.Point, point.Point) {
type candidate struct {
a, b point.Point
}
hull := convexhull.ConvexHull(points)
candidates := make([]candidate, 0)
last := 2
for i, vertex := range hull {
edge := line.ThroughPoints(vertex, hull[(i+1)%len(hull)])
for {
next := (last + 1) % len(hull)
dLast := edge.DistanceFromPoint(hull[last])
dNext := edge.DistanceFromPoint(hull[next])
if dNext < dLast {
candidates = append(candidates, candidate{vertex, hull[last]})
break
}
last = next
}
}
max := candidates[0]
for _, c := range candidates[1:] {
if point.Distance(c.a, c.b) > point.Distance(max.a, max.b) {
max = c
}
}
return max.a, max.b
}
|
package wsr
var errorMap map[int32]string = make(map[int32]string, 50)
//成功
const ERR_SUCC int32 = 0
//基础设施错误
const ERR_LOAD_LIB int32 = 1000
const ERR_INTERFACE int32 = 1002
const ERR_COM_PORT_NOTFOUND int32 = 1003
//业务错误
const ERR_UUID_LENGTH int32 = 2000
const ERR_LOAD_PSW_LEN int32 = 2001
const ERR_SET_PSW_LEN int32 = 2002
type wsrError struct {
code int32
}
func newWsrError(code int32) error {
return &wsrError{code: code}
}
func (this *wsrError) Error() string {
if this.code >= 0 && this.code < 1000 {
return "成功"
}
var ret string = "未知错误"
switch this.code {
case ERR_SUCC:
ret = "成功"
case ERR_LOAD_LIB:
ret = "链接库加载失败"
case ERR_INTERFACE:
ret = "找不到对应的函数地址"
case ERR_COM_PORT_NOTFOUND:
ret = "找不到通讯端口"
case ERR_UUID_LENGTH:
ret = "写入UUID时, 长度错误"
case ERR_LOAD_PSW_LEN:
ret = "加载密码时, 密码长度错误"
case ERR_SET_PSW_LEN:
ret = "设置密码时, 密码长度错误"
case -1:
ret = "参数值不正确"
case -10:
ret = "(仅修改密码)装载密码失败"
case -11:
ret = "(仅修改密码)读数据失败"
case -12:
ret = "(仅修改密码)写数据失败"
case -100:
ret = "写串口失败"
case -101:
ret = "读串口失败"
case -102:
ret = "接收的数据无效"
case -226:
ret = "卡不存在/卡坏"
case -227:
ret = "防冲撞错误"
case -228:
ret = "锁定卡出错"
case -229:
ret = "传密钥出错"
case -230:
ret = "密码验证出错"
case -231:
ret = "读块数据出错"
case -232:
ret = "写块数据出错"
case -233:
ret = "复位 RC500 失败"
case -234:
ret = "钱包值调入缓冲区出错"
case -235:
ret = "保存缓冲区值中的钱包值出错"
case -236:
ret = "增值出错"
case -238:
ret = "减值出错"
case -240:
ret = "块值格式不对"
case -241:
ret = "块值不够减"
case -242:
ret = "值溢出"
}
return ret
}
|
package server
import (
"2019_2_IBAT/pkg/app/auth/session"
. "2019_2_IBAT/pkg/app/chat/models"
"2019_2_IBAT/pkg/app/chat/repository"
"2019_2_IBAT/pkg/app/chat/service"
"2019_2_IBAT/pkg/pkg/config"
"2019_2_IBAT/pkg/pkg/db_connect"
"2019_2_IBAT/pkg/pkg/middleware"
"strconv"
"sync"
"net/http"
"fmt"
"log"
"github.com/google/uuid"
"github.com/gorilla/mux"
"google.golang.org/grpc"
)
func RunServer() error {
s := service.Service{
MainChan: make(chan InChatMessage, 100),
ConnectsPool: service.WsConnects{
Connects: map[uuid.UUID]*service.ConnectsPerUser{},
ConsMu: &sync.Mutex{},
},
Storage: repository.DBStorage{
DbConn: db_connect.OpenSqlxViaPgxConnPool(),
},
}
router := mux.NewRouter()
loger := middleware.NewLogger()
authGrcpConn, err := grpc.Dial(
config.AuthHostname+":"+strconv.Itoa(config.AuthServicePort),
grpc.WithInsecure(),
)
if err != nil {
log.Fatalf("cant connect to authGrcpConn")
return err
}
sessManager := session.NewServiceClient(authGrcpConn)
authMiddleware := middleware.AuthMiddlewareGenerator(sessManager)
router.Use(loger.AccessLogMiddleware)
router.Use(middleware.CorsMiddleware)
router.Use(authMiddleware)
// router.Use(middleware.CSRFMiddleware)
router.HandleFunc("/api/chat/{companion_id}", s.HandleCreateChat).Methods(http.MethodPost, http.MethodOptions)
router.HandleFunc("/api/chat/history/{id}", s.HandlerGetChatHistory).Methods(http.MethodGet, http.MethodOptions)
router.HandleFunc("/api/chat/ws", s.HandleChat)
router.HandleFunc("/api/chat/list", s.HandlerGetChats).Methods(http.MethodGet, http.MethodOptions)
for i := 0; i < config.ChatWorkers; i++ {
go s.ProcessMessage()
}
fmt.Println("starting main server at :" + strconv.Itoa(config.ChatAppPort))
log.Fatal(http.ListenAndServe(":"+strconv.Itoa(config.ChatAppPort), router))
return nil
}
|
package server
import (
"net/http"
"fmt"
"log"
oauthsvc "github.com/danielsomerfield/authful/server/service/oauth"
"time"
"github.com/danielsomerfield/authful/common/util"
"github.com/danielsomerfield/authful/server/handlers/oauth/token"
"github.com/danielsomerfield/authful/server/handlers/oauth/authorization"
"github.com/danielsomerfield/authful/server/handlers/oauth/introspection"
"github.com/danielsomerfield/authful/server/service/accesscontrol"
"github.com/danielsomerfield/authful/server/handlers/admin/client"
adminuser "github.com/danielsomerfield/authful/server/handlers/admin/user"
usersvc "github.com/danielsomerfield/authful/server/service/admin/user"
user2 "github.com/danielsomerfield/authful/server/repository/user"
"github.com/danielsomerfield/authful/server/service/crypto"
"github.com/danielsomerfield/authful/server/wire/oauth"
"github.com/danielsomerfield/authful/server/handlers/login"
)
type AuthServer struct {
port int
httpServer http.Server
running chan bool
tlsCertFile string
tlsKeyFile string
}
type Config struct {
Port int
TLS TLSConfig
}
type TLSConfig struct {
TLSCertFile string `yaml:"cert"`
TLSKeyFile string `yaml:"key"`
}
func NewAuthServer(config *Config) *AuthServer {
return &AuthServer{
port: config.Port,
tlsCertFile: config.TLS.TLSCertFile,
tlsKeyFile: config.TLS.TLSKeyFile,
}
}
func healthHandler(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("{\"status\":\"ok\"}"))
}
func (server *AuthServer) Start() (*oauthsvc.Credentials, error) {
log.Printf("Starting server up http server on port %d\n", server.port)
go func() {
httpServer := http.Server{Addr: fmt.Sprintf(":%v", server.port)}
err := httpServer.ListenAndServeTLS(server.tlsCertFile, server.tlsKeyFile)
if err != nil {
log.Fatalf("Failed to start up http server %s\n", err)
} else {
log.Printf("Server started on port %v\n", server.port)
}
server.running <- false
}()
server.running = make(chan bool)
//TODO: make generation of startup credentials a configuration option
return clientStore.RegisterClient("Root Admin", []string{"administrate", "introspect"}, nil, "")
}
func (server *AuthServer) Wait() {
<-server.running
}
func (server *AuthServer) Stop() error {
return server.httpServer.Shutdown(nil)
}
func defaultTokenGenerator() string {
return util.GenerateRandomString(25)
}
func defaultCodeGenerator() string {
return util.GenerateRandomString(6)
}
var tokenHandlerConfig = token.TokenHandlerConfig{
DefaultTokenExpiration: 3600,
}
//Injected Service Dependencies
var tokenStore = oauthsvc.NewInMemoryTokenStore()
var clientStore = oauthsvc.NewInMemoryClientStore()
var userRepository = user2.NewInMemoryUserRepository()
var approvalRequestStore = func(request *oauth.AuthorizeRequest) string {
return util.GenerateRandomString(6)
}
var loginHandler = login.NewLoginHandler()
var approvalLookup = func(approvalType string, requestId string) http.HandlerFunc {
return loginHandler
}
var defaultErrorRenderer = func(code string) []byte { //TODO: build full template renderer
return []byte(fmt.Sprintf("<html>%s</html>", code))
}
func currentTimeFn() time.Time {
return time.Now()
}
func init() {
http.HandleFunc("/token", token.NewTokenHandler(
tokenHandlerConfig,
clientStore.LookupClient,
defaultTokenGenerator,
tokenStore.StoreToken,
currentTimeFn))
http.HandleFunc("/health", healthHandler)
http.HandleFunc("/authorize", authorization.NewAuthorizationHandler(clientStore.LookupClient,
defaultErrorRenderer, approvalRequestStore, approvalLookup))
http.HandleFunc("/introspect", introspection.NewIntrospectionHandler(
accesscontrol.NewClientAccessControlFnWithScopes(clientStore.LookupClient, "introspect"), tokenStore.GetToken))
http.HandleFunc("/admin/clients", client.NewProtectedHandler(
clientStore.RegisterClient, clientStore.LookupClient))
http.HandleFunc("/admin/users", adminuser.NewProtectedHandler(
usersvc.NewRegisterUserFn(userRepository.SaveUser, crypto.ScryptHash), clientStore.LookupClient))
http.HandleFunc("/login", login.NewLoginHandler())
}
|
package binarytree
import (
"testing"
"github.com/stretchr/testify/assert"
)
func generateBinaryTree() *BinaryTree {
// generateBinaryTree() should create the following binary tree
// 10
// / \
// 5 15
// / \ / \
// 3 7 13 17
// /\ /\ / \ / \
// 1 4 6 8 11 14 16 18
bt := NewBinaryTree(10)
bt.Insert(5)
bt.Insert(15)
bt.Insert(3)
bt.Insert(7)
bt.Insert(13)
bt.Insert(17)
bt.Insert(1)
bt.Insert(4)
bt.Insert(6)
bt.Insert(8)
bt.Insert(11)
bt.Insert(14)
bt.Insert(16)
bt.Insert(18)
return bt
}
func TestGenerateBinaryTree(t *testing.T) {
assert := assert.New(t)
bt := generateBinaryTree()
// is it actually equal?
assert.EqualValues(bt.Get(), 10, "10")
assert.EqualValues(bt.GetLeft().Get(), 5, "5")
assert.EqualValues(bt.GetRight().Get(), 15, "15")
assert.EqualValues(bt.GetLeft().GetLeft().Get(), 3, "3")
assert.EqualValues(bt.GetLeft().GetRight().Get(), 7, "7")
assert.EqualValues(bt.GetRight().GetLeft().Get(), 13, "13")
assert.EqualValues(bt.GetRight().GetRight().Get(), 17, "17")
assert.EqualValues(bt.GetLeft().GetLeft().GetLeft().Get(), 1, "1")
assert.EqualValues(bt.GetLeft().GetLeft().GetRight().Get(), 4, "4")
assert.EqualValues(bt.GetLeft().GetRight().GetLeft().Get(), 6, "6")
assert.EqualValues(bt.GetLeft().GetRight().GetRight().Get(), 8, "8")
assert.EqualValues(bt.GetRight().GetLeft().GetLeft().Get(), 11, "11")
assert.EqualValues(bt.GetRight().GetLeft().GetRight().Get(), 14, "14")
assert.EqualValues(bt.GetRight().GetRight().GetLeft().Get(), 16, "16")
assert.EqualValues(bt.GetRight().GetRight().GetRight().Get(), 18, "18")
assert.Nil(bt.GetLeft().GetLeft().GetLeft().GetLeft(), "leaf!")
assert.Nil(bt.GetLeft().GetLeft().GetLeft().GetRight(), "leaf!")
assert.Nil(bt.GetLeft().GetLeft().GetRight().GetLeft(), "leaf!")
assert.Nil(bt.GetLeft().GetLeft().GetRight().GetRight(), "leaf!")
assert.Nil(bt.GetLeft().GetRight().GetLeft().GetLeft(), "leaf!")
assert.Nil(bt.GetLeft().GetRight().GetLeft().GetRight(), "leaf!")
assert.Nil(bt.GetLeft().GetRight().GetRight().GetLeft(), "leaf!")
assert.Nil(bt.GetLeft().GetRight().GetRight().GetRight(), "leaf!")
assert.Nil(bt.GetRight().GetLeft().GetLeft().GetLeft(), "leaf!")
assert.Nil(bt.GetRight().GetLeft().GetLeft().GetRight(), "leaf!")
assert.Nil(bt.GetRight().GetLeft().GetRight().GetLeft(), "leaf!")
assert.Nil(bt.GetRight().GetLeft().GetRight().GetRight(), "leaf!")
assert.Nil(bt.GetRight().GetRight().GetLeft().GetLeft(), "leaf!")
assert.Nil(bt.GetRight().GetRight().GetLeft().GetRight(), "leaf!")
assert.Nil(bt.GetRight().GetRight().GetRight().GetLeft(), "leaf!")
assert.Nil(bt.GetRight().GetRight().GetRight().GetRight(), "leaf!")
}
func TestNewBinaryTree(t *testing.T) {
assert := assert.New(t)
bt := NewBinaryTree(42)
assert.EqualValues(bt.Get(), 42)
assert.Nil(bt.GetLeft())
assert.Nil(bt.GetRight())
}
func TestBinaryTree_Set(t *testing.T) {
assert := assert.New(t)
original := NewBinaryTree(42)
original.Set(15)
assert.EqualValues(original.Get(), 15)
}
func TestBinaryTree_SetLeft(t *testing.T) {
assert := assert.New(t)
original := NewBinaryTree(42)
assist := NewBinaryTree(15)
original.SetLeft(assist)
assert.Nil(original.GetRight())
assert.EqualValues(original.GetLeft(), assist)
}
func TestBinaryTree_SetRight(t *testing.T) {
assert := assert.New(t)
original := NewBinaryTree(42)
assist := NewBinaryTree(15)
original.SetRight(assist)
assert.Nil(original.GetLeft())
assert.EqualValues(original.GetRight(), assist)
}
func TestBinaryTree_Lookup(t *testing.T) {
assert := assert.New(t)
bt := generateBinaryTree()
var lookedUp *BinaryTree
// root?
lookedUp = bt.Lookup(10)
assert.NotNil(lookedUp)
assert.EqualValues(lookedUp.Get(), 10, "root: 10")
assert.EqualValues(lookedUp.GetLeft().Get(), 5, "root: 5")
assert.EqualValues(lookedUp.GetRight().Get(), 15, "root: 15")
// middle?
lookedUp = bt.Lookup(13)
assert.NotNil(lookedUp)
assert.EqualValues(lookedUp.Get(), 13, "somewhere in the middle: 13")
assert.EqualValues(lookedUp.GetLeft().Get(), 11, "somewhere in the middle: 11")
assert.EqualValues(lookedUp.GetRight().Get(), 14, "somewhere in the middle: 14")
// leaf?
lookedUp = bt.Lookup(8)
assert.NotNil(lookedUp)
assert.EqualValues(lookedUp.Get(), 8, "leaf: 8")
assert.Nil(lookedUp.GetLeft(), "leaf")
assert.Nil(lookedUp.GetRight(), "leaf")
// none
lookedUp = bt.Lookup(9)
assert.Nil(lookedUp, "can't find")
}
func TestBinaryTree_In(t *testing.T) {
assert := assert.New(t)
bt := generateBinaryTree()
assert.True(bt.In(10))
assert.True(bt.In(13))
assert.True(bt.In(8))
assert.False(bt.In(9))
}
func TestBinaryTree_Update(t *testing.T) {
assert := assert.New(t)
bt := NewBinaryTree(10)
assert.True(bt.Update(15))
assert.Nil(bt.GetLeft())
assert.EqualValues(bt.GetRight().Get(), 15)
assert.True(bt.Update(13))
assert.Nil(bt.GetLeft())
assert.EqualValues(bt.GetRight().GetLeft().Get(), 13)
}
func TestBinaryTree_Delete(t *testing.T) {
assert := assert.New(t)
var bt *BinaryTree
var err error
// note the original
// 10
// / \
// 5 15
// / \ / \
// 3 7 13 17
// /\ /\ / \ / \
// 1 4 6 8 11 14 16 18
// delete node 10
// new tree should be
// 11
// / \
// 5 15
// / \ / \
// 3 7 13 17
// /\ /\ / \ / \
// 1 4 6 8 - 14 16 18
bt = generateBinaryTree()
bt, err = bt.Delete(10)
assert.NoError(err)
assert.EqualValues(bt.Get(), 11)
assert.EqualValues(bt.GetRight().Get(), 15)
assert.EqualValues(bt.GetRight().GetLeft().Get(), 13)
assert.Nil(bt.GetRight().GetLeft().GetLeft())
assert.EqualValues(bt.GetRight().GetLeft().GetRight().Get(), 14)
// delete node 8
// new tree should be
// 10
// / \
// 5 15
// / \ / \
// 3 7 13 17
// /\ /\ / \ / \
// 1 4 6 - 11 14 16 18
bt = generateBinaryTree()
bt, err = bt.Delete(8)
assert.NoError(err)
assert.EqualValues(bt.Get(), 10)
assert.EqualValues(bt.GetLeft().GetRight().Get(), 7)
assert.EqualValues(bt.GetLeft().GetRight().GetLeft().Get(), 6)
assert.Nil(bt.GetLeft().GetRight().GetRight())
// delete node 13
// new tree should be
// 10
// / \
// 5 15
// / \ / \
// 3 7 14 17
// /\ /\ / \ / \
// 1 4 6 8 11 - 16 18
bt = generateBinaryTree()
bt, err = bt.Delete(13)
assert.NoError(err)
assert.EqualValues(bt.Get(), 10)
assert.EqualValues(bt.GetRight().Get(), 15)
assert.EqualValues(bt.GetRight().GetLeft().Get(), 14)
assert.EqualValues(bt.GetRight().GetLeft().GetLeft().Get(), 11)
assert.Nil(bt.GetRight().GetLeft().GetRight())
// delete node 12
// this should be invalid
bt = generateBinaryTree()
bt, err = bt.Delete(12)
assert.Error(err)
assert.EqualValues(bt, generateBinaryTree())
}
|
package main
import (
"fmt"
"sort"
"strconv"
"sync"
)
// сюда писать код
func SingleHash(in, out chan interface{}) {
var muMD5 sync.Mutex
for val := range in {
data := fmt.Sprintf("%d", val)
ch_crc32_1 := dataSignerCrc32(data)
muMD5.Lock()
md5 := DataSignerMd5(data)
muMD5.Unlock()
ch_crc32_2 := dataSignerCrc32(md5)
ch_singleHash := func(crc32_1, crc32_2 chan string) chan interface{} {
out := make(chan interface{})
go func(crc32_1, crc32_2 chan string, out chan interface{}) {
out <- <-crc32_1 + "~" + <-crc32_2
}(crc32_1, crc32_2, out)
return out
}(ch_crc32_1, ch_crc32_2)
out <- ch_singleHash
}
}
func dataSignerCrc32(data string) chan string {
out := make(chan string)
go func(data string, out chan<- string) {
out <- DataSignerCrc32(data)
}(data, out)
return out
}
func MultiHash(in, out chan interface{}) {
base := 6
inProcess := make(chan interface{}, 100)
wg := &sync.WaitGroup{}
go processMultiHash(wg, inProcess, out)
for ch_singleHash := range in {
val := <-ch_singleHash.(chan interface{})
data := val.(string)
chans := make([]<-chan string, base)
for th := 0; th < base; th++ {
chans[th] = dataSignerCrc32(strconv.Itoa(th) + data)
}
wg.Add(1)
inProcess <- chans
}
wg.Wait()
close(inProcess)
}
func processMultiHash(wg *sync.WaitGroup, inProcess chan interface{}, out chan interface{}) {
for val := range inProcess {
chans := val.([]<-chan string)
multiHash := ""
for _, chanCrc := range chans {
multiHash2 := <-chanCrc
multiHash = multiHash + multiHash2
}
out <- multiHash
wg.Done()
}
}
func CombineResults(in, out chan interface{}) {
var data []string
for val := range in {
data = append(data, val.(string))
}
sort.Strings(data)
prefix := ""
combineResults := ""
for _, val := range data {
combineResults = combineResults + prefix + val
prefix = "_"
}
fmt.Println(combineResults)
out <- combineResults
}
func runner(wg *sync.WaitGroup, in, out chan interface{}, j job) {
j(in, out)
close(out)
wg.Done()
}
func ExecutePipeline(jobs ...job) {
size := 100
in := make(chan interface{}, size)
out := make(chan interface{}, size)
wg := &sync.WaitGroup{}
for _, jober := range jobs {
wg.Add(1)
go runner(wg, in, out, jober)
in = out
out = make(chan interface{}, size)
}
wg.Wait()
}
|
package evaluator
import (
"github.com/kasworld/nonkey/config/builtinfunctions"
"github.com/kasworld/nonkey/interpreter/object"
)
func init() {
builtinfunctions.BuiltinFunctions = map[string]*object.Builtin{
"version": {Fn: builtinVersion},
"args": {Fn: builtinArgs},
"chmod": {Fn: builtinChmod},
"delete": {Fn: builtinDelete},
"eval": {Fn: builtinEval},
"exit": {Fn: builtinExit},
"int": {Fn: builtinInt},
"keys": {Fn: builtinKeys},
"len": {Fn: builtinLen},
"match": {Fn: builtinMatch},
"mkdir": {Fn: builtinMkdir},
"pragma": {Fn: builtinPragma},
"open": {Fn: builtinOpen},
"push": {Fn: builtinPush},
"puts": {Fn: builtinPuts},
"printf": {Fn: builtinPrintf},
"set": {Fn: builtinSet},
"sprintf": {Fn: builtinSprintf},
"stat": {Fn: builtinStat},
"string": {Fn: builtinString},
"type": {Fn: builtinType},
"unlink": {Fn: builtinUnlink},
"os.getenv": {Fn: builtinOsGetEnv},
"os.setenv": {Fn: builtinOsSetEnv},
"os.environment": {Fn: builtinOsEnvironment},
"directory.glob": {Fn: builtinDirectoryGlob},
"math.abs": {Fn: builtinMathAbs},
"math.random": {Fn: builtinMathRandom},
"math.sqrt": {Fn: builtinMathSqrt},
}
}
|
package config
//TODO: better way https://dev.to/ilyakaznacheev/a-clean-way-to-pass-configs-in-a-go-application-1g64
// https://eltonminetto.dev/en/post/2018-06-25-golang-usando-build-tags/
//GeneralConfig GeneralConfig
type GeneralConfig struct {
DatabaseHost string
DatabaseName string
APIPort string
}
//DevConfig DevConfig
var DevConfig = GeneralConfig{DatabaseHost: "mongodb://localhost:27017", DatabaseName: "products-service", APIPort: ":8080"}
|
package main
import "fmt"
func main() {
// num1, num2 := 3,5
// 数学运算: 加减乘除
fmt.Println("请输入两个整数:")
var num1 int
var num2 int
fmt.Scanln(&num1,&num2)
//输入想要执行的操作
fmt.Println("请输入要执行的操作符号(+、-、*、/):")
var str string
fmt.Scanln(&str) // + 、 - 、* 、/
switch str { // + 、 - 、* 、/
case "+":
fmt.Println("两数相加的结果是:",num1 + num2)
case "-":
fmt.Println("两数相减的结果是:",num1 -num2)
case "*":
fmt.Println("两数相乘的结果是:",num1 * num2)
case "/":
fmt.Println("两数相除的结果是:",num1/num2)
default:
fmt.Println("对不起,我暂时不能提供您想要的操作")
}
}
|
package main
import "fmt"
func main() {
var t int
fmt.Scan(&t)
for i := 0; i < t; i++ {
var n int
fmt.Scan(&n)
// sum divisible by 3
arith3 := finiteArithmethicSum(n-1, 3)
// sum divisible by 5
arith5 := finiteArithmethicSum(n-1, 5)
// sum of duplicates
arith15 := finiteArithmethicSum(n-1, 15)
// sum = 3 plus 5 minus duplicates
sum := arith3 + arith5 - arith15
fmt.Printf("%d\n", sum)
}
}
// Sum of all numbers in range 1..limit divisable by step
func finiteArithmethicSum(limit int, step int) int {
n := limit / step
return step * ((n * (n + 1)) / 2)
}
|
package toolkit
import (
"sort"
"strings"
)
// GetFieldsNameByTag is to get an array of field names from the label value
// The parameter `source` must be a structure,
// The parameter `tagValue` specifies a structure tagValue.
func GetFieldsNameByTag(source interface{}, tagValue string) (fields []string, err error) {
stags, err := GetAllStructTags(source)
if err != nil {
return nil, err
}
for field, tags := range stags {
for _, tag := range tags {
for _, tv := range tag {
if strings.Contains(tv, ",") {
mtv := strings.Split(tv, ",")
for _, stv := range mtv {
if stv == tagValue {
fields = append(fields, field)
}
}
} else {
if tv == tagValue {
fields = append(fields, field)
}
}
}
}
}
sort.Slice(fields, func(i, j int) bool {
return fields[i] < fields[j]
})
return fields, nil
}
|
package controllers
import "github.com/gin-gonic/gin"
type IController interface {
}
type IResourceController interface {
Index(*gin.Context)
Create(*gin.Context)
Store(*gin.Context)
Show(*gin.Context)
Edit(*gin.Context)
Update(*gin.Context)
Destroy(*gin.Context)
}
func ResourceController(g *gin.RouterGroup, c IResourceController) {
//Index
g.GET("/", c.Index)
//Create New
g.GET("/create", c.Create)
//Store New
g.POST("/", c.Store)
//Show by Primary Key
g.GET("/:id", c.Show)
//Edit by Primary Key
g.GET("/:id/edit", c.Edit)
//Update by Primary Key
g.PUT("/:id", c.Update)
//Delete by Primary Key
g.DELETE("/:id", c.Destroy)
}
|
package wechat
import (
mpoauth2 "gopkg.in/chanxuehong/wechat.v2/mp/oauth2"
wxuser "gopkg.in/chanxuehong/wechat.v2/mp/user"
"gopkg.in/chanxuehong/wechat.v2/oauth2"
)
// GetUserInfo 根据微信 OpenID 获得用户信息
func (u *Wxmp) GetUserInfo(openID string) (*wxuser.UserInfo, error) {
const lang = "zh_CN"
return wxuser.Get(u.WechatClient, openID, lang)
}
// GetUserInfoByOauthCode 根据微信 OAuth 回调返回的 Code 获取对应微信用户的信息
func (u *Wxmp) GetUserInfoByOauthCode(code string) (*mpoauth2.UserInfo, error) {
oauth2Client := oauth2.Client{
Endpoint: u.Oauth2Endpoint,
}
token, err := oauth2Client.ExchangeToken(code)
if err != nil {
return nil, err
}
// 微信第三方登录验证成功,获取微信用户信息
return mpoauth2.GetUserInfo(token.AccessToken, token.OpenId, "", nil)
}
|
package main
import (
"github.com/docker/app/internal"
app "github.com/docker/app/internal/commands"
"github.com/docker/cli/cli-plugins/manager"
"github.com/docker/cli/cli-plugins/plugin"
"github.com/docker/cli/cli/command"
"github.com/spf13/cobra"
)
func main() {
plugin.Run(func(dockerCli command.Cli) *cobra.Command {
return app.NewRootCmd("app", dockerCli)
}, manager.Metadata{
SchemaVersion: "0.1.0",
Vendor: "Docker Inc.",
Version: internal.Version,
})
}
|
// Package dogmatiqapp is an practice Dogma application.
package dogmatiqapp
|
package model
import (
"github.com/jinzhu/gorm"
)
type RecordModel struct {
db *gorm.DB
}
type Record struct {
ID int `json:"id"`
DomainID int `json:"domain_id"`
Name string `json:"name"`
Type string `json:"type"`
Content string `json:"content"`
TTL int `json:"ttl"`
Prio int `json:"prio"`
Disabled *bool `json:"disabled"`
OrderName string `json:"ordername" gorm:"column:ordername"`
Auth *bool `json:"auth"`
Domain Domain `json:"-"`
}
type Records []Record
type RecordModeler interface {
FindBy(map[string]interface{}) (Records, error)
UpdateByID(string, *Record) (bool, error)
DeleteByID(string) (bool, error)
Create(*Record) error
}
func NewRecordModeler(db *gorm.DB) *RecordModel {
return &RecordModel{
db: db,
}
}
func (rs *Records) ToIntreface() []interface{} {
ret := []interface{}{}
if rs != nil {
for _, d := range *rs {
ret = append(ret, d)
}
}
return ret
}
func (d *RecordModel) FindBy(params map[string]interface{}) (Records, error) {
query := d.db.Preload("Domain")
for k, v := range params {
query = query.Where(k+" in(?)", v)
}
ds := Records{}
r := query.Find(&ds)
if r.Error != nil {
if r.RecordNotFound() {
return nil, nil
} else {
return nil, r.Error
}
}
return ds, nil
}
func (d *RecordModel) UpdateByID(id string, newRecord *Record) (bool, error) {
record := &Record{}
r := d.db.Where("id = ?", id).Take(&record)
if r.Error != nil {
if r.RecordNotFound() {
return false, nil
} else {
return false, r.Error
}
}
newRecord.DomainID = record.DomainID
r = d.db.Model(&record).Updates(&newRecord)
if r.Error != nil {
return false, r.Error
}
return true, nil
}
func (d *RecordModel) DeleteByID(id string) (bool, error) {
record := &Record{}
r := d.db.Where("id = ?", id).Take(&record)
if r.Error != nil {
if r.RecordNotFound() {
return false, nil
} else {
return false, r.Error
}
}
r = d.db.Delete(record)
if r.Error != nil {
return false, r.Error
}
return true, nil
}
func (d *RecordModel) Create(newRecord *Record) error {
f := false
if newRecord.Disabled == nil {
newRecord.Disabled = &f
}
if newRecord.Auth == nil {
newRecord.Auth = &f
}
if err := d.db.Create(newRecord).Error; err != nil {
return err
}
return nil
}
|
package main
import (
"fmt"
)
func main() {
s1 := []int{1}
fmt.Println("s1 = ", s1)
fmt.Printf("s1: len = %d, cap = %d\n", len(s1), cap(s1))
// append函数,是向切片末尾追加元素,并且返回一个新的切片
s1 = append(s1, 2)
fmt.Println("s1 = ", s1)
fmt.Printf("s1: len = %d, cap = %d\n", len(s1), cap(s1))
s1 = append(s1, 3)
fmt.Println("s1 = ", s1)
fmt.Printf("s1: len = %d, cap = %d\n", len(s1), cap(s1))
// 结果为:
// s1 = [1]
// s1: len = 1, cap = 1
// s1 = [1 2]
// s1: len = 2, cap = 2
// s1 = [1 2 3]
// s1: len = 3, cap = 4
// 结论:
// append是往切入末尾追加元素,并且返回一个新的切片,同时如果超出了容量大小,容量会翻倍增加
s2 := []int{1, 2}
s3 := []int{3, 4, 5, 6}
// copy函数,是将s2内容复制到s3中相应的位置
copy(s3, s2)
fmt.Println("s3 = ", s3)
// 结果为:
// s3 = [1 2 5 6]
}
|
// Go support for Protocol Buffers RPC which compatiable with https://github.com/Baidu-ecom/Jprotobuf-rpc-socket
//
// Copyright 2002-2007 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package link
import "net"
type Server struct {
manager *Manager
listener net.Listener
protocol Protocol
handler Handler
sendChanSize int
IdleTimeoutSenconds *int
}
type Handler interface {
HandleSession(*Session)
}
// var name type = value .
var _ Handler = HandlerFunc(nil)
type HandlerFunc func(*Session)
func (f HandlerFunc) HandleSession(session *Session) {
f(session)
}
func NewServer(listener net.Listener, protocol Protocol, sendChanSize int, handler Handler) *Server {
return &Server{
manager: NewManager(),
listener: listener,
protocol: protocol,
handler: handler,
sendChanSize: sendChanSize,
}
}
func (server *Server) Listener() net.Listener {
return server.listener
}
func (server *Server) Serve() error {
for {
conn, err := Accept(server.listener)
if err != nil {
return err
}
go func() {
codec, err := server.protocol.NewCodec(conn)
if err != nil {
conn.Close()
return
}
codec.SetTimeout(server.IdleTimeoutSenconds)
session := server.manager.NewSession(codec, server.sendChanSize)
session.IdleTimeoutSenconds = server.IdleTimeoutSenconds
server.handler.HandleSession(session)
}()
}
}
func (server *Server) GetSession(sessionID uint64) *Session {
return server.manager.GetSession(sessionID)
}
func (server *Server) Stop() {
server.listener.Close()
server.manager.Dispose()
}
|
package main
import (
"fmt"
"log"
"net"
)
func main() {
host, _, err := net.SplitHostPort("127.0.0.1:12345")
if err != nil {
log.Fatalln(err)
}
addr := net.ParseIP(host)
if addr == nil {
println("not valid ip")
} else {
fmt.Printf("ip: %s\n", addr)
}
}
|
package main
import (
"context"
"database/sql"
"fmt"
"log"
"math/rand"
"time"
"github.com/Rican7/retry"
"github.com/Rican7/retry/backoff"
"github.com/Rican7/retry/jitter"
"github.com/Rican7/retry/strategy"
)
func doQuery(ctx context.Context, db *sql.DB, runnerId string) {
ticker := time.NewTicker(10 * time.Millisecond)
for {
select {
case <-ticker.C:
query(ctx, db, runnerId)
}
}
}
func query(ctx context.Context, db *sql.DB, runnerId string) {
d := time.Now().Add(20 * time.Second)
ctx, cancel := context.WithDeadline(context.Background(), d)
defer timeTrack(time.Now(), fmt.Sprintf("query - %s", runnerId))
defer cancel()
row := db.QueryRow(queryStatement)
var result string
seed := time.Now().UnixNano()
random := rand.New(rand.NewSource(seed))
action := func(attempt uint) error {
var err error
if err := row.Scan(&result); err != nil {
log.Printf("Query [%s] Attenpt (%d) - %s", runnerId, attempt, err.Error())
}
if err == nil {
log.Printf("%s - Retrieved successfully %s.\n", runnerId, result)
}
return err
}
err := retry.Retry(
action,
strategy.Limit(2000),
strategy.BackoffWithJitter(backoff.Linear(10*time.Millisecond), jitter.Deviation(random, 0.8)),
)
if err != nil {
log.Fatalf("Query[%s] Error: %v", runnerId, err.Error())
}
//Check context for error, If ctx.Err() != nil gracefully exit the current execution
if ctx.Err() != nil {
log.Fatalf("query[%s]- %v \n", runnerId, ctx.Err())
}
}
|
package main
func main() {
}
func postorderTraversal(root *TreeNode) (res []int) {
addPath := func(node *TreeNode) {
path := []int{}
for ; node != nil; node = node.Right {
path = append(path, node.Val)
}
for i := len(path) - 1; i >= 0; i-- {
res = append(res, path[i])
}
}
p1 := root
for p1 != nil {
if p2 := p1.Left; p2 != nil {
for p2.Right != nil && p2.Right != p1 {
p2 = p2.Right
}
if p2.Right == nil {
p2.Right = p1
p1 = p1.Left
continue
}
p2.Right = nil
addPath(p1.Left)
}
p1 = p1.Right
}
addPath(root)
return
}
|
package main
import "fmt"
// type person struct {
// name string
// age int
// }
// func newPerson(name string, age int) person {
// return person{
// name: name,
// age: age,
// }
// }
// func (p person) older() {
// p.age++
// }
// func (p *person) oldert() {
// //(*p).age++
// p.age++ //语法糖
// }
// func main() {
// s1 := newPerson("xiaoming", 18)
// s1.older()
// fmt.Println(s1)
// //(&s1).oldert()
// s1.oldert()
// fmt.Println(s1)
// }
//不能给别的包里面的类型添加方法,只能给自己包里面的类型添加方法
type myInt int
func (m *myInt) biger() {
*m++
}
func main() {
s1 := myInt(10)
fmt.Printf("type:%T,value:%v\n", s1, s1)
//(&s1).biger()
s1.biger() //语法糖
fmt.Printf("type:%T,value:%v\n", s1, s1)
}
|
package quark
import (
"log"
"net/http"
"time"
)
// 用户请求拦截器
func UserRequestInterceptor(ct Context) error {
token := ct.GetAccessToken()
if token == "" {
return Next
}
// 令牌校验
user, has := VerifyAccessToken(token)
if !has {
return ct.To401()
}
if user != "" {
ct.User = user
ct.Request.Header.Add(AccessTokenHeader, ct.User)
} else {
return Next
}
// 超频拦截
if _, has := interceptor[ct.User]; has {
return ct.ToJson(1102, "请求超频")
}
// 在线状态检测
if conn, has := online[ct.User]; !has {
// return ct.ToJson(1100, "当前状态为离线")
} else {
if conn.Limit > 25 {
// 请求频繁锁定账户1分钟,5秒内请求超过25次
__interceptorSet(ct.User, time.Minute)
} else {
// 请求+1
conn.Limit = conn.Limit + 1
onlineMx.Lock()
online[ct.User] = conn
onlineMx.Unlock()
}
}
return Next
}
func __interceptorSet(k string, expire time.Duration) {
if _, has := interceptor[k]; !has {
interceptorMx.Lock()
interceptor[k] = nil
interceptorMx.Unlock()
if expire != 0 {
go func(k string, expire time.Duration) {
time.Sleep(expire)
delete(interceptor, k)
}(k, expire)
}
}
}
// 用户在线状态机
func UserOnlineStateMachine(ct Context) error {
user, has := VerifyAccessToken(ct.Query("at"))
if !has {
return ct.To401()
}
if user != "" {
__userOnlineStateMachine(ct.Response, ct.Request, user)
}
return ct.ToJson(200, "长连接结束")
}
func __userOnlineStateMachine(w http.ResponseWriter, r *http.Request, user string) {
conn, e := upGrader.Upgrade(w, r, nil)
if e != nil {
panic(e)
} else {
defer conn.Close()
if this, has := online[user]; !has {
// 用户上线
online[user] = onlineStruct{WsConn: conn}
__onlineLog(online1, user)
} else {
// 发送下线通知
if e = online[user].WsConn.WriteMessage(1, []byte("1100")); e != nil {
log.Printf("[ error ] %s\n", e.Error())
return
}
_ = online[user].WsConn.Close()
// 用户重新上线
this.WsConn = conn
online[user] = this
__onlineLog(online2, user)
}
}
// 心跳
for {
time.Sleep(time.Second * 1)
if e = conn.WriteMessage(1, []byte("200")); e != nil {
break
}
_, msg, _ := conn.ReadMessage()
if string(msg) != "200" {
// 心跳异常,下线处理
_ = online[user].WsConn.Close()
delete(online, user)
__onlineLog(online3, user)
break
}
}
}
func __onlineLog(event int, user string) {
log.Printf("[ ONLINE ] (%d) %s\n", event, user)
}
|
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"time"
"log"
"os"
_"strings"
_"context"
"net/http"
"golang.org/x/crypto/bcrypt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/joho/godotenv"
"github.com/dgrijalva/jwt-go"
)
type Exception struct{
Message string `json:"message"`
}
type User struct {
gorm.Model
Email string `json:"email"`
Password string `json:"password"`
}
type Claims struct {
UserID uint
Email string
*jwt.StandardClaims
}
// Connecting to the DB
func ConnectDB() *gorm.DB{
err := godotenv.Load()
if err != nil{
log.Fatal("Error in Loading Page")
}
username := os.Getenv("db_user")
password := os.Getenv("db_password")
dbname := os.Getenv("db_name")
dbHost := os.Getenv("db_host")
dbUri := fmt.Sprintf("host=%s user=%s dbname=%s sslmode=disable password=%s", dbHost, username, dbname, password) //Build connection string
fmt.Println(dbUri)
db, err :=gorm.Open("postgres", dbUri)
if err != nil{
fmt.Println("Error")
}
defer db.Close()
db.AutoMigrate(User{})
fmt.Println("SuccessFully Connected")
return db
}
var db = ConnectDB()
type ErrorResponse struct {
Err string
}
type error interface {
Error() string
}
//Creating The User
func CreateUser(w http.ResponseWriter, r *http.Request){
user := &User{}
json.NewDecoder(r.Body).Decode(user)
pass, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
if err!=nil{
fmt.Println(err)
err:= ErrorResponse{
Err: "Password Encryption Failed",
}
json.NewEncoder(w).Encode(err)
}
user.Password = string(pass)
createdUser := db.Create(user)
//var errMessage = createdUser.Error
if createdUser.Error != nil{
fmt.Println("Error")
}
json.NewEncoder(w).Encode(createdUser)
}
//Login
func Login(w http.ResponseWriter, r *http.Request) {
user := &User{}
err := json.NewDecoder(r.Body).Decode(user)
if err != nil {
var resp = map[string]interface{}{"status": false, "message": "Invalid request"}
json.NewEncoder(w).Encode(resp)
return
}
resp := Find(user.Email, user.Password)
json.NewEncoder(w).Encode(resp)
}
func Find(email, password string) map[string]interface{} {
user := &User{}
if err := db.Where("Email = ?", email).First(user).Error; err != nil {
var resp = map[string]interface{}{"status": false, "message": "Email address not found"}
return resp
}
expiresAt := time.Now().Add(time.Minute * 100000).Unix()
errf := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
if errf != nil && errf == bcrypt.ErrMismatchedHashAndPassword { //Password does not match!
var resp = map[string]interface{}{"status": false, "message": "Invalid login credentials. Please try again"}
return resp
}
tk := &Claims{
UserID: user.ID,
Email: user.Email,
StandardClaims: &jwt.StandardClaims{
ExpiresAt: expiresAt,
},
}
token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), tk)
tokenString, error := token.SignedString([]byte("secret"))
if error != nil {
fmt.Println(error)
}
var resp = map[string]interface{}{"status": false, "message": "logged in"}
resp["token"] = tokenString //Store the token in the response
resp["user"] = user
return resp
}
func main(){
router := mux.NewRouter()
router.HandleFunc("/register", CreateUser).Methods("POST")
router.HandleFunc("/login", Login).Methods("POST")
log.Fatal(http.ListenAndServe(":8000", router))
}
|
package main
import (
"ms/sun/servises/file_service/file_common"
"net/url"
"ms/sun/shared/helper"
)
func main() {
url, _ := url.Parse("http://localhost:5151/post_file/1518506476136010007_180.jpg")
req := file_common.NewRowReq(file_common.HttpCategories[1], url)
//helper.PertyPrintNew(req)
helper.PertyPrint(req)
url, _ = url.Parse("http://localhost:5151/post_file/1518506476136010007.mov")
req = file_common.NewRowReq(file_common.HttpCategories[1], url)
req.SetNewFileDataStoreId(5000000000)
//helper.PertyPrintNew(req)
helper.PertyPrint(req)
}
|
package routers
import (
"github.com/gin-gonic/gin"
"net/http"
"regexp"
)
func InitRouter() *gin.Engine {
router := gin.Default()
router.Use(CorsMiddleware())
router.GET("/test", func(ctx *gin.Context) {
ctx.String(200, "its working")
})
SetNoteRouter(router)
SetMemberRouter(router)
SetTagRouter(router)
return router
}
func CorsMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
origin := c.Request.Header.Get("Origin")
var filterHost = [...]string{"http://localhost.*"}
// filterHost 做过滤器,防止不合法的域名访问
var isAccess = false
for _, v := range filterHost {
match, _ := regexp.MatchString(v, origin)
if match {
isAccess = true
}
}
if isAccess {
// 核心处理方式
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Headers", "*")
c.Header("Access-Control-Allow-Methods", "GET, OPTIONS, POST, PUT, DELETE")
c.Set("content-type", "application/json")
}
//放行所有OPTIONS方法
if method == "OPTIONS" {
//c.JSON(http.StatusNoContent, "Options Request!")
c.AbortWithStatus(http.StatusNoContent)
}
c.Next()
}
}
|
package main
import (
"fmt"
"log"
"sync"
)
var wg1 sync.WaitGroup
func init() {
log.SetFlags(log.Lshortfile)
}
func producer1(sch chan<- int) {
defer wg1.Done()
for i := 0; i < 10; i++ {
sch <- i
fmt.Printf("ch<------生产 %d\n", i)
}
close(sch)
}
func consumer1(rch <-chan int) {
defer wg1.Done()
for v := range rch {
fmt.Printf("消费 %d\n", v)
}
}
func main() {
wg1.Add(2)
ch := make(chan int)
go producer1(ch)
go consumer1(ch)
wg1.Wait()
}
|
/*
Package slack is a Connection to the Slack Real Time Messaging API
(https://api.slack.com/rtm). To use this connection, you will need
to create a custom bot user. See https://api.slack.com/bot-users#custom_bot_users.
Once you've created a bot user, you will need to initialize the Slack connection
using the API key for this bot user.
slackConnection := NewConnection("MySlackBotAPIKey")
*/
package slack
import (
"encoding/json"
"errors"
"github.com/handwritingio/deckard-bot/log"
"github.com/handwritingio/deckard-bot/message"
"golang.org/x/net/websocket"
)
// Connection provides an interface for storing the Slack API key and the inbox for storing received messages
type Connection struct {
Token string
Inbox map[int]Message
}
// Message provides the interface for all Slack messages
type Message struct {
message.Basic
Type string `json:"type"`
Channel string `json:"channel"`
User string `json:"user"`
Timestamp string `json:"ts"`
}
// NewConnection returns a new Connection to Slack
func NewConnection(slackAPIKey string) *Connection {
return &Connection{
slackAPIKey,
make(map[int]Message),
}
}
// Start creates the connection for the Slack RTM and creates the transmit and receive
// goroutines that listen and send messages through the tx and rx channels
func (s *Connection) Start(errorChannel chan error) (rx, tx message.BasicChannel) {
rx = make(message.BasicChannel)
tx = make(message.BasicChannel)
wssurl, err := getWSSUrl(s.Token)
if err != nil {
errorChannel <- err
panic(err) // TODO
}
// Connect to the websocket
ws, err := websocket.Dial(wssurl, "", "http://localhost/")
if err != nil {
log.Fatal(err)
}
// defer ws.Close() // TODO
// start message Id generator
msgChan := messageIDGen(0, 1)
// run keepalive to keep the websocket connection running
go keepalive(ws, msgChan)
// start the RX and TX methods
go s.startRX(ws, rx, errorChannel)
go s.startTX(ws, tx, msgChan, errorChannel)
return rx, tx
}
// startRX listens to all Slack messages. It adds all messages of type 'message' to the inbox and
// adds the message with text only (m.Basic) to the rx channel. Messages send into the rx channel
// are sent to the messagePump, which sends the message to each plugin
func (s *Connection) startRX(ws *websocket.Conn, rx message.BasicChannel, errorChannel chan error) {
// get info of bot
BotID, err := apiTokenAuthTest(s.Token)
if err != nil {
errorChannel <- err
}
// run infinite loop for receiving messages
counter := 0
for {
var raw json.RawMessage
err := websocket.JSON.Receive(ws, &raw)
if err != nil {
errorChannel <- err
}
var event struct {
Type string `json:"type"`
Error json.RawMessage `json:"error"`
ReplyTo int `json:"reply_to"`
}
err = json.Unmarshal(raw, &event)
if err != nil {
errorChannel <- err
}
switch event.Type {
case "":
log.Debug("Acknowledge message: ", event.ReplyTo)
case "pong", "presence_change", "user_typing", "reconnect_url":
continue
case "hello":
// Send response to hello straight into websocket without going through messagePump
log.Debug("Hello Event: ", event.Type)
case "message":
var m Message
err = json.Unmarshal(raw, &m)
if err != nil {
errorChannel <- err
}
m.Basic.Text = formatSlackMsg(m.Basic.Text)
log.Debugf("Full msg: %v\n", m)
// if the message is not from the configured Bot
// we don't want the bot responding to its own messages
if m.User != BotID {
// returns response string
m.Basic.ID = counter
s.Inbox[counter] = m
rx <- m.Basic
counter++
}
}
}
}
// startTX is responsible for listening on the tx channel and sending all non-blank messages back through the
// websocket connection. The outgoing message is reassembled from the text from the tx channel and the rest of
// the original message attributes. Since this is the Slack startTX, it add a mention before the text to alert
// user that sent the original message that the bot has responded
func (s *Connection) startTX(ws *websocket.Conn, tx message.BasicChannel, msgChan <-chan int, errorChannel chan error) {
for {
select {
case msg := <-tx:
// handle everything except blank messages
if msg.Text != "" {
out, ok := s.Inbox[msg.ID]
if ok != true {
errorChannel <- errors.New("unknown id")
}
// get the UserId from the message sent
// Add it to the beginning of the text
msgUser := "<@" + out.User + ">: "
out.Text = msgUser + msg.Text
id := <-msgChan
out.ID = id
// send response struct
err := websocket.JSON.Send(ws, &out)
if err != nil {
errorChannel <- err
}
if msg.Finished {
delete(s.Inbox, msg.ID)
}
log.Debug("inbox size: ", len(s.Inbox))
}
}
}
}
|
// Copyright 2018 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package memo
import (
"encoding/binary"
"reflect"
"testing"
"github.com/pingcap/tidb/expression"
plannercore "github.com/pingcap/tidb/planner/core"
"github.com/stretchr/testify/require"
)
func TestNewGroupExpr(t *testing.T) {
p := &plannercore.LogicalLimit{}
expr := NewGroupExpr(p)
require.Equal(t, p, expr.ExprNode)
require.Nil(t, expr.Children)
require.False(t, expr.Explored(0))
}
func TestGroupExprFingerprint(t *testing.T) {
p := &plannercore.LogicalLimit{Count: 3}
expr := NewGroupExpr(p)
childGroup := NewGroupWithSchema(nil, expression.NewSchema())
expr.SetChildren(childGroup)
// ChildNum(2 bytes) + ChildPointer(8 bytes) + LogicalLimit HashCode
planHash := p.HashCode()
buffer := make([]byte, 10+len(planHash))
binary.BigEndian.PutUint16(buffer, 1)
binary.BigEndian.PutUint64(buffer[2:], uint64(reflect.ValueOf(childGroup).Pointer()))
copy(buffer[10:], planHash)
require.Equal(t, string(buffer), expr.FingerPrint())
}
|
package models
import (
"github.com/labstack/echo/v4"
"net/http"
)
type httpContext struct {
c echo.Context
}
type Response struct {
Code int `json:"code"`
MessageCode int `json:"message_code"`
Message string `json:"message"`
Data interface{} `json:"data"`
}
type Result struct {
Data interface{} `json:"data"`
Error error `json:"error"`
}
func ToJSON(c echo.Context) *httpContext {
httpContext := &httpContext{c}
return httpContext
}
func (httpContext httpContext) Ok(data interface{}, msg string) error {
return httpContext.c.JSON(http.StatusOK, Response{
Code: http.StatusOK,
Message: msg,
Data: data,
})
}
func (httpContext httpContext) InternalServerError(msg string) error {
return httpContext.c.JSON(http.StatusInternalServerError, &Response{
Code: http.StatusBadRequest,
Message: msg,
Data: nil,
})
}
func (httpContext httpContext) BadRequest(msg string) error {
return httpContext.c.JSON(http.StatusBadRequest, &Response{
Code: http.StatusBadRequest,
Message: msg,
Data: nil,
})
}
func (httpContext httpContext) StatusNotFound(msg string) error {
return httpContext.c.JSON(http.StatusNotFound, &Response{
Code: http.StatusNotFound,
Message: msg,
Data: nil,
})
}
|
package mongodb
import (
"gopkg.in/mgo.v2"
"sync"
)
var (
ins *mgo.Session
conErr error
once sync.Once
dbUrl string
)
// 实例化Mongo
func Connect() *mgo.Session {
once.Do(func() {
dbUrl = "mongodb://myuser:mypass@localhost:40001,otherhost:40001/mydb"
ins, conErr = mgo.Dial("localhost:27017")
if conErr != nil {
ins = nil
}
})
return ins
}
// 销毁实例
func Close() {
ins.Close()
} |
package main
import (
"fmt"
"net/http"
"os"
"os/exec"
"strings"
"time"
"github.com/go-redis/redis"
"github.com/gocolly/colly"
)
const (
restockurl = "https://www.queens.cz/kat/2/boty-tenisky-panske/?sort=new"
)
type product struct {
ID, Name, Price, Thumb, URL string
}
func atc(id, name, url, price, thumb string) {
webhook1 := "https://monitors.blazingfa.st/queens/?token=Q3CFLMnPMWiszuKedCLD"
client := &http.Client{}
data := `{
"name": "` + name + `",
"thumb": "` + thumb + `",
"price": "` + price + `",
"id": "` + id + `",
"url": "` + url + `"
}`
req, _ := http.NewRequest("POST", webhook1, strings.NewReader(data))
req.Header.Add("content-type", "application/json")
_, _ = client.Do(req)
}
// // Products from the Queens sitemap
// type Products struct {
// URL []struct {
// Loc string `xml:"loc"`
// Image []struct {
// Loc string `xml:"loc"`
// Title string `xml:"title"`
// } `xml:"image"`
// } `xml:"url"`
// }
// func parsexml() {
// // xmlFile, err := os.Open("2.changed.xml")
// // if err != nil {
// // fmt.Println(err)
// // }
// // defer xmlFile.Close()
// // byteValue, _ := ioutil.ReadAll(xmlFile)
// response, err := http.Get("https://www.queens.cz/sitemap/index/2")
// if err != nil {
// panic(err)
// }
// defer response.Body.Close()
// contents, err := ioutil.ReadAll(response.Body)
// var products Products
// xml.Unmarshal(contents, &products)
// for i := 0; i < len(products.URL); i++ {
// arr := strings.Split(products.URL[i].Loc, "/")
// arr = append(arr[:3], arr[4:]...) // remove wear
// arr = append(arr[:4], arr[5:]...) // remove number after id
// fmt.Println(strings.Join(arr, "/"))
// }
// }
// var products []product
func getproducts(url string) []product {
var products []product
c := colly.NewCollector()
c.OnHTML("#categoryItems", func(e *colly.HTMLElement) {
e.ForEach(".category-item", func(i int, child *colly.HTMLElement) {
// sk/global
// fmt.Println(child.ChildAttr("a", "data-name"))
// cz
var p product
p.ID = strings.Split(child.ChildAttr("a", "href"), "/")[4]
p.Name = child.ChildAttr("a img", "alt")
p.Thumb = child.ChildAttr("a img.imgr", "data-src")
p.Price = child.ChildText(".price")
p.URL = child.ChildAttr("a", "href")
products = append(products, p)
})
})
c.Visit(url)
return products
}
func testEq(a, b []string) bool {
if (a == nil) != (b == nil) {
return false
}
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
func helper() {
}
func main() {
restockDB := redis.NewClient(&redis.Options{
Addr: "SG-queens-28130.servers.mongodirector.com:6379",
Password: "1RUYz0QuhgujaCOKORYmdIa2xrm9Xj7a",
DB: 1,
})
// soldoutDB := redis.NewClient(&redis.Options{
// Addr: "localhost:6379",
// Password: "",
// DB: 1,
// })
for {
{
os.Setenv("HTTP_PROXY", "http://hicoria:samosa44@74.231.59.117:2000")
restocks := getproducts(restockurl)
// soldouts := getproducts(lasturl)
fmt.Println("monitoring for new products")
for _, p := range restocks {
_, err := restockDB.Get(p.ID).Result()
if err == redis.Nil {
fmt.Println("new product found:", p.Name)
atc(p.ID, p.Name, p.URL, p.Price, p.Thumb)
// err := client.Set(p.ID, strings.Join(p.Sizes, "##"), 0).Err()
err = restockDB.Set(p.ID, p.Name, 0).Err()
if err != nil {
panic(err)
}
} else if err != nil {
panic(err)
}
}
}
time.Sleep(1 * time.Second)
}
}
|
package logs
import (
"bufio"
"context"
"sort"
"strings"
"sync"
"time"
log "github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
apierr "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/kubernetes"
workflowpkg "github.com/argoproj/argo/pkg/apiclient/workflow"
wfv1 "github.com/argoproj/argo/pkg/apis/workflow/v1alpha1"
"github.com/argoproj/argo/pkg/client/clientset/versioned"
"github.com/argoproj/argo/workflow/common"
)
// The goal of this class is to stream the logs of the workflow you want.
// * If you request "follow" and the workflow is not completed: logs will be tailed until the workflow is completed or context done.
// * Otherwise, it will print recent logs and exit.
type request interface {
GetNamespace() string
GetName() string
GetPodName() string
GetLogOptions() *corev1.PodLogOptions
}
type sender interface {
Send(entry *workflowpkg.LogEntry) error
}
func WorkflowLogs(ctx context.Context, wfClient versioned.Interface, kubeClient kubernetes.Interface, req request, sender sender) error {
wfInterface := wfClient.ArgoprojV1alpha1().Workflows(req.GetNamespace())
_, err := wfInterface.Get(req.GetName(), metav1.GetOptions{})
if err != nil {
return err
}
podInterface := kubeClient.CoreV1().Pods(req.GetNamespace())
logCtx := log.WithFields(log.Fields{"workflow": req.GetName(), "namespace": req.GetNamespace()})
// we create a watch on the pods labelled with the workflow name,
// but we also filter by pod name if that was requested
podListOptions := metav1.ListOptions{LabelSelector: common.LabelKeyWorkflow + "=" + req.GetName()}
if req.GetPodName() != "" {
podListOptions.FieldSelector = "metadata.name=" + req.GetPodName()
}
logCtx.WithField("options", podListOptions).Debug("List options")
// Keep a track of those we are logging, we also have a mutex to guard reads. Even if we stop streaming, we
// keep a marker here so we don't start again.
streamedPods := make(map[types.UID]bool)
var streamedPodsGuard sync.Mutex
var wg sync.WaitGroup
// A non-blocking channel for log entries to go down.
unsortedEntries := make(chan logEntry, 128)
logOptions := req.GetLogOptions()
if logOptions == nil {
logOptions = &corev1.PodLogOptions{}
}
logOptions.Timestamps = true
// this func start a stream if one is not already running
ensureWeAreStreaming := func(pod *corev1.Pod) {
streamedPodsGuard.Lock()
defer streamedPodsGuard.Unlock()
logCtx := logCtx.WithField("podName", pod.GetName())
logCtx.WithFields(log.Fields{"podPhase": pod.Status.Phase, "alreadyStreaming": streamedPods[pod.UID]}).Debug("Ensuring pod logs stream")
if pod.Status.Phase != corev1.PodPending && !streamedPods[pod.UID] {
streamedPods[pod.UID] = true
wg.Add(1)
go func(podName string) {
defer wg.Done()
logCtx.Debug("Streaming pod logs")
defer logCtx.Debug("Pod logs stream done")
stream, err := podInterface.GetLogs(podName, logOptions).Stream()
if err != nil {
logCtx.Error(err)
return
}
scanner := bufio.NewScanner(stream)
for scanner.Scan() {
select {
case <-ctx.Done():
return
default:
line := scanner.Text()
parts := strings.SplitN(line, " ", 2)
content := parts[1]
timestamp, err := time.Parse(time.RFC3339, parts[0])
if err != nil {
logCtx.Errorf("unable to decode or infer timestamp from log line: %s", err)
// The current timestamp is the next best substitute. This won't be shown, but will be used
// for sorting
timestamp = time.Now()
content = line
}
// You might ask - why don't we let the client do this? Well, it is because
// this is the same as how this works for `kubectl logs`
if req.GetLogOptions().Timestamps {
content = line
}
logCtx.WithFields(log.Fields{"timestamp": timestamp, "content": content}).Debug("Log line")
unsortedEntries <- logEntry{podName: podName, content: content, timestamp: timestamp}
}
}
logCtx.Debug("No more log lines to stream")
// out of data, we do not want to start watching again
}(pod.GetName())
}
}
podWatch, err := podInterface.Watch(podListOptions)
if err != nil {
return err
}
defer podWatch.Stop()
// only list after we start the watch
logCtx.Debug("Listing workflow pods")
list, err := podInterface.List(podListOptions)
if err != nil {
return err
}
// start watches by start-time
sort.Slice(list.Items, func(i, j int) bool {
return list.Items[i].Status.StartTime.Before(list.Items[j].Status.StartTime)
})
for _, pod := range list.Items {
ensureWeAreStreaming(&pod)
}
if req.GetLogOptions().Follow {
wfListOptions := metav1.ListOptions{FieldSelector: "metadata.name=" + req.GetName()}
wfWatch, err := wfInterface.Watch(wfListOptions)
if err != nil {
return err
}
defer wfWatch.Stop()
// We never send anything on this channel apart from closing it to indicate we should stop waiting for new pods.
stopWatchingPods := make(chan struct{})
// The purpose of this watch is to make sure we do not exit until the workflow is completed or deleted.
// When that happens, it signals we are done by closing the stop channel.
wg.Add(1)
go func() {
defer close(stopWatchingPods)
defer wg.Done()
defer logCtx.Debug("Done watching workflow events")
logCtx.Debug("Watching for workflow events")
for {
select {
case <-ctx.Done():
return
case event, open := <-wfWatch.ResultChan():
if !open {
logCtx.Debug("Re-establishing workflow watch")
wfWatch.Stop()
wfWatch, err = wfInterface.Watch(wfListOptions)
if err != nil {
logCtx.Error(err)
return
}
continue
}
wf, ok := event.Object.(*wfv1.Workflow)
if !ok {
// object is probably probably metav1.Status
logCtx.WithError(apierr.FromObject(event.Object)).Warn("watch object was not a workflow")
return
}
logCtx.WithFields(log.Fields{"eventType": event.Type, "completed": wf.Status.Fulfilled()}).Debug("Workflow event")
if event.Type == watch.Deleted || wf.Status.Fulfilled() {
return
}
// in case we re-establish the watch, make sure we start at the same place
wfListOptions.ResourceVersion = wf.ResourceVersion
}
}
}()
// The purpose of this watch is to start streaming any new pods that appear when we are running.
wg.Add(1)
go func() {
defer wg.Done()
defer logCtx.Debug("Done watching pod events")
logCtx.Debug("Watching for pod events")
for {
select {
case <-stopWatchingPods:
return
case event, open := <-podWatch.ResultChan():
if !open {
logCtx.Info("Re-establishing pod watch")
podWatch.Stop()
podWatch, err = podInterface.Watch(podListOptions)
if err != nil {
logCtx.Error(err)
return
}
continue
}
pod, ok := event.Object.(*corev1.Pod)
if !ok {
// object is probably probably metav1.Status
logCtx.WithError(apierr.FromObject(event.Object)).Warn("watch object was not a pod")
return
}
logCtx.WithFields(log.Fields{"eventType": event.Type, "podName": pod.GetName(), "phase": pod.Status.Phase}).Debug("Pod event")
if pod.Status.Phase == corev1.PodRunning {
ensureWeAreStreaming(pod)
}
podListOptions.ResourceVersion = pod.ResourceVersion
}
}
}()
} else {
logCtx.Debug("Not starting watches")
}
doneSorting := make(chan struct{})
go func() {
defer close(doneSorting)
defer logCtx.Debug("Done sorting entries")
logCtx.Debug("Sorting entries")
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
entries := logEntries{}
// Ugly to have this func, but we use it in two places (normal operation and finishing up).
send := func() error {
sort.Sort(entries)
for len(entries) > 0 {
// head
var e logEntry
e, entries = entries[0], entries[1:]
logCtx.WithFields(log.Fields{"timestamp": e.timestamp, "content": e.content}).Debug("Sending entry")
err := sender.Send(&workflowpkg.LogEntry{Content: e.content, PodName: e.podName})
if err != nil {
return err
}
}
return nil
}
// This defer make sure we flush any remaining entries on exit.
defer func() {
err := send()
if err != nil {
logCtx.Error(err)
}
}()
for {
select {
case entry, ok := <-unsortedEntries:
if !ok {
// The fact this channel is closed indicates that we need to finish-up.
return
} else {
entries = append(entries, entry)
}
case <-ticker.C:
err := send()
if err != nil {
logCtx.Error(err)
return
}
}
}
}()
logCtx.Debug("Waiting for work-group")
wg.Wait()
logCtx.Debug("Work-group done")
close(unsortedEntries)
<-doneSorting
logCtx.Debug("Done-done")
return nil
}
|
package main
import (
"context"
"fmt"
"go.etcd.io/etcd/clientv3"
"time"
)
func main() {
cli, err := clientv3.New(clientv3.Config {
Endpoints: []string{"127.0.0.1:2379"}, // etcd的节点,可以传入多个
DialTimeout: 5*time.Second, // 连接超时时间
})
if err != nil {
fmt.Printf("connect to etcd failed, err: %v \n", err)
return
}
fmt.Println("connect to etcd success")
// 延迟关闭
defer cli.Close()
// put操作 设置1秒超时
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
value := `[{"path":"D:/mogu_blog/logs/mysql.log","topic":"web_log"},{"path":"D:/mogu_blog/logs/redis.log","topic":"redis_log"}]`
_, err = cli.Put(ctx, "/logagent/202.193.57.73/collect_config", value)
cancel()
if err != nil {
fmt.Printf("put to etcd failed, err:%v \n", err)
return
}
fmt.Println("设置成功")
} |
/*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package tasks
import (
"context"
"fmt"
"strconv"
"strings"
"time"
"github.com/Tencent/bk-bcs/bcs-common/common/blog"
proto "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/api/clustermanager"
"github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/internal/cloudprovider"
"github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/internal/cloudprovider/qcloud/api"
"github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/internal/common"
"github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/internal/remote/loop"
"github.com/avast/retry-go"
as "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/as/v20180419"
tke "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/tke/v20180525"
)
// ApplyInstanceMachinesTask update desired nodes task
func ApplyInstanceMachinesTask(taskID string, stepName string) error {
start := time.Now()
// get task and task current step
state, step, err := cloudprovider.GetTaskStateAndCurrentStep(taskID, stepName)
if err != nil {
return err
}
// previous step successful when retry task
if step == nil {
return nil
}
// extract parameter && check validate
clusterID := step.Params[cloudprovider.ClusterIDKey.String()]
nodeGroupID := step.Params[cloudprovider.NodeGroupIDKey.String()]
cloudID := step.Params[cloudprovider.CloudIDKey.String()]
desiredNodes := step.Params[cloudprovider.ScalingNodesNumKey.String()]
manual := state.Task.CommonParams[cloudprovider.ManualKey.String()]
nodeNum, _ := strconv.Atoi(desiredNodes)
operator := step.Params[cloudprovider.OperatorKey.String()]
if len(clusterID) == 0 || len(nodeGroupID) == 0 || len(cloudID) == 0 || len(desiredNodes) == 0 || len(operator) == 0 {
blog.Errorf("ApplyInstanceMachinesTask[%s]: check parameter validate failed", taskID)
retErr := fmt.Errorf("ApplyInstanceMachinesTask check parameters failed")
_ = cloudprovider.DeleteVirtualNodes(clusterID, nodeGroupID, taskID)
_ = cloudprovider.UpdateNodeGroupDesiredSize(nodeGroupID, nodeNum, true)
_ = state.UpdateStepFailure(start, stepName, retErr)
return retErr
}
dependInfo, err := cloudprovider.GetClusterDependBasicInfo(cloudprovider.GetBasicInfoReq{
ClusterID: clusterID,
CloudID: cloudID,
NodeGroupID: nodeGroupID,
})
if err != nil {
blog.Errorf("ApplyInstanceMachinesTask[%s]: GetClusterDependBasicInfo failed: %s", taskID, err.Error())
retErr := fmt.Errorf("ApplyInstanceMachinesTask GetClusterDependBasicInfo failed")
if manual == common.True {
_ = cloudprovider.UpdateVirtualNodeStatus(clusterID, nodeGroupID, taskID)
} else {
_ = cloudprovider.UpdateNodeGroupDesiredSize(nodeGroupID, nodeNum, true)
}
_ = state.UpdateStepFailure(start, stepName, retErr)
return retErr
}
// inject taskID
ctx := cloudprovider.WithTaskIDForContext(context.Background(), taskID)
activity, err := applyInstanceMachines(ctx, dependInfo, uint64(nodeNum))
if err != nil {
blog.Errorf("ApplyInstanceMachinesTask[%s]: applyInstanceMachines failed: %s", taskID, err.Error())
retErr := fmt.Errorf("ApplyInstanceMachinesTask applyInstanceMachines failed %s", err.Error())
if manual == common.True {
_ = cloudprovider.UpdateVirtualNodeStatus(clusterID, nodeGroupID, taskID)
} else {
_ = cloudprovider.UpdateNodeGroupDesiredSize(nodeGroupID, nodeNum, true)
}
_ = state.UpdateStepFailure(start, stepName, retErr)
return retErr
}
// trans success nodes to cm DB and record common paras, not handle error
err = recordClusterInstanceToDB(ctx, activity, state, dependInfo, uint64(nodeNum))
if err != nil {
blog.Errorf("ApplyInstanceMachinesTask[%s]: recordClusterInstanceToDB failed: %s",
taskID, err.Error())
retErr := fmt.Errorf("ApplyInstanceMachinesTask applyInstanceMachines failed %s", err.Error())
if manual == common.True {
_ = cloudprovider.UpdateVirtualNodeStatus(clusterID, nodeGroupID, taskID)
} else {
_ = cloudprovider.UpdateNodeGroupDesiredSize(nodeGroupID, nodeNum, true)
}
_ = state.UpdateStepFailure(start, stepName, retErr)
return retErr
}
// destroy virtual nodes
if manual == common.True {
blog.Infof("ApplyInstanceMachinesTask[%s] begin DeleteVirtualNodes", taskID)
_ = cloudprovider.DeleteVirtualNodes(clusterID, nodeGroupID, taskID)
}
// update step
if err := state.UpdateStepSucc(start, stepName); err != nil {
blog.Errorf("ApplyInstanceMachinesTask[%s] task %s %s update to storage fatal", taskID, taskID, stepName)
return err
}
return nil
}
// applyInstanceMachines apply machines from asg
func applyInstanceMachines(ctx context.Context, info *cloudprovider.CloudDependBasicInfo, nodeNum uint64) (*as.Activity, error) {
taskID := cloudprovider.GetTaskIDFromContext(ctx)
var (
asgID, activityID string
activity *as.Activity
err error
)
asgID, err = getAsgIDByNodePool(ctx, info)
if err != nil {
return nil, fmt.Errorf("applyInstanceMachines[%s] getAsgIDByNodePool failed: %v", taskID, err)
}
asCli, err := api.NewASClient(info.CmOption)
if err != nil {
return nil, err
}
// get asgActivityID
err = loop.LoopDoFunc(context.Background(), func() error {
activityID, err = asCli.ScaleOutInstances(asgID, nodeNum)
if err != nil {
if strings.Contains(err.Error(), as.RESOURCEUNAVAILABLE_AUTOSCALINGGROUPINACTIVITY) {
blog.Infof("applyInstanceMachines[%s] ScaleOutInstances: %v", taskID, as.RESOURCEUNAVAILABLE_AUTOSCALINGGROUPINACTIVITY)
return nil
}
blog.Errorf("applyInstanceMachines[%s] ScaleOutInstances failed: %v", taskID, err)
return err
}
return loop.EndLoop
}, loop.LoopInterval(10*time.Second))
if err != nil || activityID == "" {
return nil, fmt.Errorf("applyInstanceMachines[%s] ScaleOutInstances failed: %v", taskID, err)
}
ctx, cancel := context.WithTimeout(ctx, 10*time.Minute)
defer cancel()
// get activityID status
err = loop.LoopDoFunc(ctx, func() error {
activity, err = asCli.DescribeAutoScalingActivities(activityID)
if err != nil {
blog.Errorf("taskID[%s] DescribeAutoScalingActivities[%s] failed: %v", taskID, activityID, err)
return nil
}
switch *activity.StatusCode {
case api.SuccessfulActivity.String(), api.SuccessfulPartActivity.String():
blog.Infof("taskID[%s] DescribeAutoScalingActivities[%s] status[%s]",
taskID, activityID, *activity.StatusCode)
return loop.EndLoop
case api.FailedActivity.String():
return fmt.Errorf("taskID[%s] DescribeAutoScalingActivities[%s] failed, cause: %v, message: %v",
taskID, activityID, *activity.Cause, *activity.StatusMessage)
case api.CancelledActivity.String():
return fmt.Errorf("taskID[%s] DescribeAutoScalingActivities[%s] failed: %v", taskID, activityID, api.CancelledActivity.String())
default:
blog.Infof("taskID[%s] DescribeAutoScalingActivities[%s] still creating, status[%s]",
taskID, activityID, *activity.StatusCode)
return nil
}
}, loop.LoopInterval(30*time.Second))
if err != nil {
blog.Errorf("taskID[%s] applyInstanceMachines[%s] failed: %v", taskID, activityID, err)
return nil, err
}
return activity, nil
}
// recordClusterInstanceToDB already auto build instances to cluster, thus not handle error
func recordClusterInstanceToDB(ctx context.Context, activity *as.Activity, state *cloudprovider.TaskState,
info *cloudprovider.CloudDependBasicInfo, nodeNum uint64) error {
// get success instances
var (
successInstanceID []string
failedInstanceID []string
)
taskID := cloudprovider.GetTaskIDFromContext(ctx)
for _, ins := range activity.ActivityRelatedInstanceSet {
if *ins.InstanceStatus == api.SuccessfulInstanceAS.String() {
successInstanceID = append(successInstanceID, *ins.InstanceId)
} else {
failedInstanceID = append(failedInstanceID, *ins.InstanceId)
}
}
// rollback desired num && delete failed nodes
if len(successInstanceID) != int(nodeNum) {
_ = destroyAsgInstances(ctx, info, *activity.AutoScalingGroupId, failedInstanceID)
_ = cloudprovider.UpdateNodeGroupDesiredSize(info.NodeGroup.NodeGroupID, int(nodeNum)-len(successInstanceID), true)
}
// record instanceIDs to task common
if state.Task.CommonParams == nil {
state.Task.CommonParams = make(map[string]string)
}
if len(successInstanceID) > 0 {
state.Task.CommonParams[cloudprovider.SuccessNodeIDsKey.String()] = strings.Join(successInstanceID, ",")
state.Task.CommonParams[cloudprovider.NodeIDsKey.String()] = strings.Join(successInstanceID, ",")
}
if len(failedInstanceID) > 0 {
state.Task.CommonParams[cloudprovider.FailedNodeIDsKey.String()] = strings.Join(failedInstanceID, ",")
}
if len(successInstanceID) == 0 {
blog.Errorf("recordClusterInstanceToDB[%s] successInstanceID empty", taskID)
return fmt.Errorf("successInstanceID empty")
}
// record successNodes to cluster manager DB
nodeIPs, err := transInstancesToNode(ctx, successInstanceID, info)
if err != nil {
blog.Errorf("recordClusterInstanceToDB[%s] failed: %v", taskID, err)
}
if len(nodeIPs) > 0 {
state.Task.NodeIPList = nodeIPs
state.Task.CommonParams[cloudprovider.OriginNodeIPsKey.String()] = strings.Join(nodeIPs, ",")
state.Task.CommonParams[cloudprovider.NodeIPsKey.String()] = strings.Join(nodeIPs, ",")
}
return nil
}
// transInstancesToNode record success nodes to cm DB
func transInstancesToNode(ctx context.Context, successInstanceID []string, info *cloudprovider.CloudDependBasicInfo) ([]string, error) {
var (
cvmCli = api.NodeManager{}
nodes = make([]*proto.Node, 0)
nodeIPs = make([]string, 0)
err error
)
taskID := cloudprovider.GetTaskIDFromContext(ctx)
err = retry.Do(func() error {
nodes, err = cvmCli.ListNodesByInstanceID(successInstanceID, &cloudprovider.ListNodesOption{
Common: info.CmOption,
ClusterVPCID: info.Cluster.VpcID,
})
if err != nil {
return err
}
return nil
}, retry.Attempts(3))
if err != nil {
blog.Errorf("transInstancesToNode[%s] failed: %v", taskID, err)
return nil, err
}
for _, n := range nodes {
nodeIPs = append(nodeIPs, n.InnerIP)
n.ClusterID = info.NodeGroup.ClusterID
n.NodeGroupID = info.NodeGroup.NodeGroupID
n.Passwd = info.NodeGroup.LaunchTemplate.InitLoginPassword
n.Status = common.StatusInitialization
err = cloudprovider.SaveNodeInfoToDB(ctx, n, false)
if err != nil {
blog.Errorf("transInstancesToNode[%s] SaveNodeInfoToDB[%s] failed: %v", taskID, n.InnerIP, err)
}
}
return nodeIPs, nil
}
// destroyAsgInstances destroy Asg instances
func destroyAsgInstances(ctx context.Context, info *cloudprovider.CloudDependBasicInfo,
asgId string, instances []string) error {
taskID := cloudprovider.GetTaskIDFromContext(ctx)
asCli, err := api.NewASClient(info.CmOption)
if err != nil {
blog.Errorf("destroyAsgInstances[%s] removeInstance[%s] failed: %v", taskID, instances, err)
return err
}
_, err = asCli.RemoveInstances(asgId, instances)
if err != nil {
blog.Errorf("destroyAsgInstances[%s] removeInstance[%s] failed: %v", taskID, instances, err)
return err
}
return nil
}
func getAsgIDByNodePool(ctx context.Context, info *cloudprovider.CloudDependBasicInfo) (string, error) {
taskID := cloudprovider.GetTaskIDFromContext(ctx)
nodePoolID := info.NodeGroup.CloudNodeGroupID
tkeCli, err := api.NewTkeClient(info.CmOption)
if err != nil {
return "", err
}
var (
pool *tke.NodePool
)
err = retry.Do(
func() error {
pool, err = tkeCli.DescribeClusterNodePoolDetail(info.Cluster.SystemID, nodePoolID)
if err != nil {
return err
}
return nil
},
retry.Context(ctx), retry.Attempts(3),
)
if err != nil {
blog.Errorf("applyInstancesFromNodePool[%s] failed: %v", taskID, err)
return "", err
}
return *pool.AutoscalingGroupId, nil
}
// CheckClusterNodesStatusTask check update desired nodes status task. nodes already add to cluster, thus not rollback desiredNum and only record status
func CheckClusterNodesStatusTask(taskID string, stepName string) error {
start := time.Now()
// get task and task current step
state, step, err := cloudprovider.GetTaskStateAndCurrentStep(taskID, stepName)
if err != nil {
return err
}
// previous step successful when retry task
if step == nil {
return nil
}
// step login started here
// extract parameter && check validate
clusterID := step.Params[cloudprovider.ClusterIDKey.String()]
nodeGroupID := step.Params[cloudprovider.NodeGroupIDKey.String()]
cloudID := step.Params[cloudprovider.CloudIDKey.String()]
successInstanceID := cloudprovider.ParseNodeIpOrIdFromCommonMap(state.Task.CommonParams,
cloudprovider.SuccessNodeIDsKey.String(), ",")
manual := state.Task.CommonParams[cloudprovider.ManualKey.String()]
if len(clusterID) == 0 || len(nodeGroupID) == 0 || len(cloudID) == 0 || len(successInstanceID) == 0 {
blog.Errorf("CheckClusterNodesStatusTask[%s]: check parameter validate failed", taskID)
retErr := fmt.Errorf("CheckClusterNodesStatusTask check parameters failed")
_ = state.UpdateStepFailure(start, stepName, retErr)
return retErr
}
dependInfo, err := cloudprovider.GetClusterDependBasicInfo(cloudprovider.GetBasicInfoReq{
ClusterID: clusterID,
CloudID: cloudID,
NodeGroupID: nodeGroupID,
})
if err != nil {
blog.Errorf("CheckClusterNodesStatusTask[%s]: GetClusterDependBasicInfo failed: %s", taskID, err.Error())
retErr := fmt.Errorf("CheckClusterNodesStatusTask GetClusterDependBasicInfo failed")
_ = state.UpdateStepFailure(start, stepName, retErr)
return retErr
}
// inject taskID
ctx := cloudprovider.WithTaskIDForContext(context.Background(), taskID)
successInstances, failureInstances, err := CheckClusterInstanceStatus(ctx, dependInfo, successInstanceID)
if err != nil || len(successInstances) == 0 {
if manual != common.True {
// rollback failed nodes
_ = returnInstancesAndCleanNodes(ctx, dependInfo, successInstanceID)
}
blog.Errorf("CheckClusterNodesStatusTask[%s]: checkClusterInstanceStatus failed: %s", taskID, err.Error())
retErr := fmt.Errorf("CheckClusterNodesStatusTask checkClusterInstanceStatus failed")
_ = state.UpdateStepFailure(start, stepName, retErr)
return retErr
}
// rollback abnormal nodes
if len(failureInstances) > 0 {
blog.Errorf("CheckClusterNodesStatusTask[%s] handle failedNodes[%v]", taskID, failureInstances)
errMsg := returnInstancesAndCleanNodes(ctx, dependInfo, failureInstances)
if errMsg != nil {
blog.Errorf("CheckClusterNodesStatusTask[%s] returnInstancesAndCleanNodes failed %v", taskID, errMsg)
}
}
blog.Infof("CheckClusterNodeStatusTask[%s] delivery succeed[%d] instances[%v] failed[%d] instances[%v]",
taskID, len(successInstances), successInstances, len(failureInstances), failureInstances)
// trans instanceIDs to ipList
ipList := cloudprovider.GetInstanceIPsByID(ctx, successInstances)
// update response information to task common params
if state.Task.CommonParams == nil {
state.Task.CommonParams = make(map[string]string)
}
if len(successInstances) > 0 {
state.Task.CommonParams[cloudprovider.SuccessClusterNodeIDsKey.String()] = strings.Join(successInstances, ",")
}
if len(failureInstances) > 0 {
state.Task.CommonParams[cloudprovider.FailedClusterNodeIDsKey.String()] = strings.Join(failureInstances, ",")
}
// successInstance ip list
if len(ipList) > 0 {
state.Task.CommonParams[cloudprovider.DynamicNodeIPListKey.String()] = strings.Join(ipList, ",")
state.Task.CommonParams[cloudprovider.NodeIPsKey.String()] = strings.Join(ipList, ",")
state.Task.NodeIPList = ipList
}
// update step
if err := state.UpdateStepSucc(start, stepName); err != nil {
blog.Errorf("CheckClusterNodesStatusTask[%s] task %s %s update to storage fatal", taskID, taskID, stepName)
return err
}
return nil
}
func returnInstancesAndCleanNodes(ctx context.Context, info *cloudprovider.CloudDependBasicInfo, instanceIDs []string) error {
taskID := cloudprovider.GetTaskIDFromContext(ctx)
if len(instanceIDs) == 0 {
blog.Infof("returnInstancesAndCleanNodes[%s] instanceIDs empty", taskID)
return nil
}
// delete db data record
for _, instanceID := range instanceIDs {
err := cloudprovider.GetStorageModel().DeleteClusterNode(context.Background(), info.Cluster.ClusterID, instanceID)
if err != nil {
blog.Errorf("returnInstancesAndCleanNodes[%s] DeleteClusterNode[%s] failed: %v", taskID, instanceID, err)
} else {
blog.Infof("returnInstancesAndCleanNodes[%s] DeleteClusterNode success[%+v]", taskID, instanceID)
}
}
// delete instances
err := removeAsgInstances(ctx, info, instanceIDs)
if err != nil {
blog.Errorf("returnInstancesAndCleanNodes[%s] removeAsgInstances[%+v] "+
"failed: %v", taskID, instanceIDs, err)
} else {
blog.Infof("returnInstancesAndCleanNodes[%s] removeAsgInstances[%+v] success", taskID, instanceIDs)
}
// rollback nodeGroup desired size
err = cloudprovider.UpdateNodeGroupDesiredSize(info.NodeGroup.NodeGroupID, len(instanceIDs), true)
if err != nil {
blog.Errorf("returnInstancesAndCleanNodes[%s] UpdateNodeGroupDesiredSize failed: %v", taskID, err)
} else {
blog.Infof("returnInstancesAndCleanNodes[%s] UpdateNodeGroupDesiredSize success[%v]", taskID, len(instanceIDs))
}
return nil
}
|
package main
import (
"fmt"
"strconv"
)
func main() {
var _ = Valid("")
}
func Valid(ccNumber string) (valid bool) {
// ccNumber = "378282246310005"
ccNumber = "4539148803436467"
ccInt, err := strconv.Atoi(ccNumber)
if err != nil {
return false
}
cardDigits := []int{}
for ccInt > 0 {
cardDigits = append(cardDigits, ccInt%10)
ccInt = ccInt / 10
}
for i := 1; i < len(cardDigits); i++ {
if i%2 == 0 {
continue
}
newValue := cardDigits[i] * 2
if newValue > 9 {
newValue -= 9
}
cardDigits[i] = newValue
}
var sum int
for _, digit := range cardDigits {
sum += digit
}
fmt.Printf("Result: %v \n", cardDigits)
fmt.Printf("Sum: %v \n", sum)
return sum%10 == 0
}
|
package main
// OK! 3'54
import (
"bufio"
"fmt"
"os"
"strconv"
)
var sc = bufio.NewScanner(os.Stdin)
func nextInt() int {
sc.Scan()
i, e := strconv.Atoi(sc.Text())
if e != nil {
panic(e)
}
return i
}
func main() {
/* 初期化開始 */
sc.Split(bufio.ScanWords)
x := nextInt()
y := nextInt()
/* 初期化終了 */
fmt.Printf("%d\n", y/x)
}
|
/**
*@Author: haoxiongxiao
*@Date: 2019/2/2
*@Description: CREATE GO FILE sms_api_services
*/
package sms_api_services
import (
"bysj/models"
"bysj/models/redi"
"github.com/garyburd/redigo/redis"
"github.com/lexkong/log"
"github.com/spf13/viper"
"github.com/xhaoxiong/ShowApiSdk/normalRequest"
)
type SmsApiService struct {
redi *redis.Pool
}
func NewSmsApiService() *SmsApiService {
return &SmsApiService{redi: models.GetRedis()}
}
const (
appId = 58443
appSecret = "3bd66623713248bab7c97eabe481bbcd"
)
func (this *SmsApiService) SendSms(code, mobile string) {
res := normalRequest.ShowapiRequest("http://route.showapi.com/28-1", appId, appSecret)
res.AddTextPara("mobile", mobile)
res.AddTextPara("content", "{\"name\":\""+mobile+"\",\"code\":\""+code+"\",\"minute\":\"3\",\"comName\":\"毕设酒店预订平台\"}")
res.AddTextPara("tNum", "T150606060601")
res.AddTextPara("big_msg", "")
_, err := res.Post()
if err == nil {
redi.Set(mobile, code)
redi.SetExpire(mobile, viper.GetString("sms_expire"))
} else {
log.Errorf(err, "发送失败\n")
}
}
|
package mutexs
import (
"testing"
)
func TestMutexChannel(t*testing.T){
MutexChannel()
}
func TestMutexChannelBuffer(t*testing.T){
MutexChannelBuffer()
} |
package dcp
// Given an integer n, return the length of the longest consecutive run of 1s in its binary representation.
// For example, given 156, you should return 3.
func longestConsecutive1s(n int) int {
longest, current := 0, 0
for n > 0 {
r := n % 2
n /= 2
if r == 0 {
current = 0
} else {
current++
}
if current > longest {
longest = current
}
}
return longest
}
|
package day6
import (
"fmt"
)
func part1(a_tree *tree) int {
sum := 0
for _, node := range a_tree.nodes {
sum += node.depth
}
return sum
}
func part2(a_tree *tree) int {
n_transfers := 0
you, san := a_tree.nodes["YOU"].parent, a_tree.nodes["SAN"].parent
for you.depth < san.depth {
san = san.parent
n_transfers += 1
}
for san.depth < you.depth {
you = you.parent
n_transfers += 1
}
for san != you {
san, you = san.parent, you.parent
n_transfers += 2
}
return n_transfers
}
func Solve() error {
tree, err := readTree("./input/6.txt")
if err != nil {
return err
}
fmt.Println("Day 6, Part 1. Calculate total number of direct and indirect orbits of all objects in our map.")
fmt.Println(" ", part1(&tree))
fmt.Println("Day 6, Part 2. Calculate number of orbital transfers needed to reach Santa.")
fmt.Println(" ", part2(&tree))
return nil
}
|
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
package cni
import (
"flag"
"fmt"
"os"
"runtime"
"github.com/aws/amazon-vpc-cni-plugins/capabilities"
"github.com/aws/amazon-vpc-cni-plugins/logger"
"github.com/aws/amazon-vpc-cni-plugins/version"
log "github.com/cihub/seelog"
cniSkel "github.com/containernetworking/cni/pkg/skel"
cniTypes "github.com/containernetworking/cni/pkg/types"
cniVersion "github.com/containernetworking/cni/pkg/version"
)
// Plugin is the base class to all CNI plugins.
type Plugin struct {
Name string
SpecVersions cniVersion.PluginInfo
LogFilePath string
Commands API
Capability *capabilities.Capability
}
// NewPlugin creates a new CNI Plugin object.
func NewPlugin(
name string,
specVersions cniVersion.PluginInfo,
logFilePath string,
cmds API) (*Plugin, error) {
return &Plugin{
Name: name,
SpecVersions: specVersions,
LogFilePath: logFilePath,
Commands: cmds,
Capability: capabilities.New(),
}, nil
}
// Initialize initializes the CNI plugin.
func (plugin *Plugin) Initialize() error {
// Configure logging.
logger.Setup(plugin.LogFilePath)
return nil
}
// Uninitialize frees the resources in the CNI plugin.
func (plugin *Plugin) Uninitialize() {
}
// Run starts the CNI plugin.
func (plugin *Plugin) Run() *cniTypes.Error {
defer log.Flush()
// Parse command line arguments.
var printVersion, printCapabilities bool
flag.BoolVar(&printVersion, version.Command, false, "prints version and exits")
flag.BoolVar(&printCapabilities, capabilities.Command, false, "prints capabilities and exits")
flag.Parse()
if printVersion {
err := plugin.printVersionInfo()
if err != nil {
os.Stderr.WriteString(fmt.Sprintf("Failed to print version: %v", err))
return nil
}
return nil
}
if printCapabilities {
err := plugin.Capability.Print()
if err != nil {
os.Stderr.WriteString(fmt.Sprintf("Failed to print capabilities: %v", err))
return nil
}
return nil
}
// Ensure that goroutines do not change OS threads during namespace operations.
runtime.LockOSThread()
defer runtime.UnlockOSThread()
// Recover from panics.
defer func() {
if r := recover(); r != nil {
buf := make([]byte, 1<<12)
len := runtime.Stack(buf, false)
cniErr := &cniTypes.Error{
Code: 100,
Msg: fmt.Sprintf("%v", r),
Details: string(buf[:len]),
}
cniErr.Print()
log.Errorf("Recovered panic: %v %v\n", cniErr.Msg, cniErr.Details)
}
}()
log.Infof("Plugin %s version %s executing CNI command.", plugin.Name, version.Version)
// Execute CNI command handlers.
cniErr := cniSkel.PluginMainWithError(
plugin.Commands.Add,
plugin.Commands.Check,
plugin.Commands.Del,
plugin.Commands.GetVersion(),
plugin.Name)
if cniErr != nil {
log.Errorf("CNI command failed: %+v", cniErr)
}
return cniErr
}
// Add is an empty CNI ADD command handler to ensure all CNI plugins implement CNIAPI.
func (plugin *Plugin) Add(args *cniSkel.CmdArgs) error {
return nil
}
// Check is an empty CNI CHECK command handler to ensure all CNI plugins implement CNIAPI.
func (plugin *Plugin) Check(args *cniSkel.CmdArgs) error {
return nil
}
// Del is an empty CNI DEL command handler to ensure all CNI plugins implement CNIAPI.
func (plugin *Plugin) Del(args *cniSkel.CmdArgs) error {
return nil
}
// GetVersion is the default CNI VERSION command handler.
func (plugin *Plugin) GetVersion() cniVersion.PluginInfo {
return plugin.SpecVersions
}
// printVersionInfo prints the plugin version.
func (plugin *Plugin) printVersionInfo() error {
versionInfo, err := version.String()
if err != nil {
return err
}
fmt.Println(versionInfo)
return nil
}
|
package alibabacloud
import (
"fmt"
"strings"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/validation/field"
"github.com/openshift/installer/pkg/types"
alibabacloudtypes "github.com/openshift/installer/pkg/types/alibabacloud"
)
// Validate executes platform-specific validation.
func Validate(client *Client, ic *types.InstallConfig) error {
allErrs := field.ErrorList{}
platformPath := field.NewPath("platform").Child("alibabacloud")
allErrs = append(allErrs, validatePlatform(client, ic, platformPath)...)
allErrs = append(allErrs, validateControlPlaneMachinePool(client, ic)...)
allErrs = append(allErrs, validateComputeMachinePool(client, ic)...)
return allErrs.ToAggregate()
}
func validateControlPlaneMachinePool(client *Client, ic *types.InstallConfig) field.ErrorList {
allErrs := field.ErrorList{}
mpool := mergedMachinePool{}
defaultPool := alibabacloudtypes.DefaultMasterMachinePoolPlatform()
mpool.setWithFieldPath(&defaultPool, field.NewPath("controlPlane", "platform", "alibabacloud"))
if ic.Platform.AlibabaCloud != nil {
mpool.setWithFieldPath(ic.Platform.AlibabaCloud.DefaultMachinePlatform, field.NewPath("platform", "alibabacloud", "defaultMachinePlatform"))
}
mpool.setWithFieldPath(ic.ControlPlane.Platform.AlibabaCloud, field.NewPath("controlPlane", "platform", "alibabacloud"))
allErrs = append(allErrs, validateMachinePool(client, ic, &mpool)...)
return allErrs
}
func validateComputeMachinePool(client *Client, ic *types.InstallConfig) field.ErrorList {
allErrs := field.ErrorList{}
for idx, compute := range ic.Compute {
mpool := mergedMachinePool{}
computePoolFieldPath := field.NewPath("compute").Index(idx).Child("platform", "alibabacloud")
defaultPool := alibabacloudtypes.DefaultWorkerMachinePoolPlatform()
mpool.setWithFieldPath(&defaultPool, computePoolFieldPath)
if ic.Platform.AlibabaCloud != nil {
mpool.setWithFieldPath(ic.Platform.AlibabaCloud.DefaultMachinePlatform, field.NewPath("platform", "alibabacloud", "defaultMachinePlatform"))
}
if compute.Platform.AlibabaCloud != nil {
mpool.setWithFieldPath(compute.Platform.AlibabaCloud, computePoolFieldPath)
}
allErrs = append(allErrs, validateMachinePool(client, ic, &mpool)...)
}
return allErrs
}
func validateMachinePool(client *Client, ic *types.InstallConfig, pool *mergedMachinePool) field.ErrorList {
allErrs := field.ErrorList{}
if len(pool.Zones) > 0 {
availableZones := map[string]bool{}
response, err := client.DescribeAvailableResource("Zone")
if err != nil {
return append(allErrs, field.InternalError(pool.zonesFieldPath, err))
}
for _, availableZone := range response.AvailableZones.AvailableZone {
if availableZone.Status == "Available" {
availableZones[availableZone.ZoneId] = true
}
}
for idx, zone := range pool.Zones {
if !availableZones[zone] {
allErrs = append(allErrs, field.Invalid(pool.zonesFieldPath.Index(idx), zone, fmt.Sprintf("zone ID is unavailable in region %q", ic.Platform.AlibabaCloud.Region)))
}
}
}
// InstanceType and zones are related.
// If the availability zone is not available, the instanceType will not be validated.
if len(allErrs) == 0 {
allErrs = append(allErrs, validateInstanceType(client, pool.Zones, pool.InstanceType, pool.instanceTypeFieldPath)...)
}
return allErrs
}
func validateInstanceType(client *Client, zones []string, instanceType string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
availableZones, err := client.GetAvailableZonesByInstanceType(instanceType)
if err != nil {
return append(allErrs, field.InternalError(fldPath, err))
}
if len(zones) == 0 && len(availableZones) == 0 {
return append(allErrs, field.Invalid(fldPath, instanceType, "no available availability zones found"))
}
zonesWithStock := sets.NewString(availableZones...)
for _, zoneID := range zones {
if !zonesWithStock.Has(zoneID) {
allErrs = append(allErrs, field.Invalid(fldPath, instanceType, fmt.Sprintf("instance type is out of stock or unavailable in zone %q", zoneID)))
}
}
return allErrs
}
func validatePlatform(client *Client, ic *types.InstallConfig, path *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if ic.AlibabaCloud.ResourceGroupID != "" {
allErrs = append(allErrs, validateResourceGroup(client, ic, path)...)
}
if ic.AlibabaCloud.VpcID != "" {
allErrs = append(allErrs, validateVpc(client, ic, path)...)
}
if len(ic.AlibabaCloud.VSwitchIDs) != 0 {
allErrs = append(allErrs, validateVSwitches(client, ic, path)...)
}
if ic.AlibabaCloud.PrivateZoneID != "" {
allErrs = append(allErrs, validatePrivateZoneID(client, ic, path)...)
}
return allErrs
}
func validateResourceGroup(client *Client, ic *types.InstallConfig, path *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
resourceGroupID := ic.AlibabaCloud.ResourceGroupID
resourceGroups, err := client.ListResourceGroups(resourceGroupID)
if err != nil {
if strings.Contains(err.Error(), "InvalidParameter.ResourceGroupId") {
return append(allErrs, field.Invalid(path.Child("resourceGroupID"), resourceGroupID, "resourceGroupID is invalid"))
}
return append(allErrs, field.InternalError(path.Child("resourceGroupID"), err))
}
if resourceGroups.TotalCount == 0 {
return append(allErrs, field.NotFound(path.Child("resourceGroupID"), ic.AlibabaCloud.ResourceGroupID))
}
return allErrs
}
func validateVpc(client *Client, ic *types.InstallConfig, path *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
vpcs, err := client.ListVpcs(ic.AlibabaCloud.VpcID)
if err != nil {
return append(allErrs, field.InternalError(path.Child("vpcID"), err))
}
if vpcs.TotalCount == 0 {
allErrs = append(allErrs, field.NotFound(path.Child("vpcID"), ic.AlibabaCloud.VpcID))
}
return allErrs
}
func validateVSwitches(client *Client, ic *types.InstallConfig, path *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
zoneIDs := map[string]bool{}
for idx, id := range ic.AlibabaCloud.VSwitchIDs {
vswitches, err := client.ListVSwitches(id)
if err != nil {
return append(allErrs, field.InternalError(path.Child("vswitchIDs"), err))
}
if vswitches.TotalCount != 1 {
allErrs = append(allErrs, field.NotFound(path.Child("vswitchIDs").Index(idx), id))
continue
}
vswitch := vswitches.VSwitches.VSwitch[0]
if vswitch.VpcId != ic.AlibabaCloud.VpcID {
allErrs = append(allErrs, field.Invalid(path.Child("vswitchIDs").Index(idx), id, fmt.Sprintf("the VSwitch does not belong to vpc %s", ic.AlibabaCloud.VpcID)))
}
if zoneIDs[vswitch.ZoneId] {
allErrs = append(allErrs, field.Invalid(path.Child("vswitchIDs").Index(idx), id, "the availability zone of the VSwitch overlapped with other VSwitches"))
} else {
zoneIDs[vswitch.ZoneId] = true
}
}
return allErrs
}
func validatePrivateZoneID(client *Client, ic *types.InstallConfig, path *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
fldpath := path.Child("privateZoneID")
zoneName := ic.ClusterDomain()
isExist := false
zones, err := client.ListPrivateZonesByVPC(ic.AlibabaCloud.VpcID)
if err != nil {
return append(allErrs, field.InternalError(fldpath, err))
}
for _, zone := range zones.Zones.Zone {
if zone.ZoneId == ic.AlibabaCloud.PrivateZoneID {
isExist = true
if zone.ZoneName != zoneName {
allErrs = append(allErrs, field.Invalid(fldpath, ic.AlibabaCloud.PrivateZoneID, fmt.Sprintf("the name %s of the existing private zone does not match the expected zone name %s", zone.ZoneName, zoneName)))
}
break
}
}
if !isExist {
return append(allErrs, field.Invalid(fldpath, ic.AlibabaCloud.PrivateZoneID, fmt.Sprintf("the private zone is not found, or not associated with the VPC %s", ic.AlibabaCloud.VpcID)))
}
return allErrs
}
// ValidateForProvisioning validates if the install config is valid for provisioning the cluster.
func ValidateForProvisioning(client *Client, ic *types.InstallConfig, metadata *Metadata) error {
allErrs := field.ErrorList{}
allErrs = append(allErrs, validateClusterName(client, ic)...)
allErrs = append(allErrs, validateNatGateway(client, ic)...)
return allErrs.ToAggregate()
}
func validateClusterName(client *Client, ic *types.InstallConfig) field.ErrorList {
allErrs := field.ErrorList{}
if ic.AlibabaCloud.PrivateZoneID != "" {
return allErrs
}
namePath := field.NewPath("metadata").Child("name")
zoneName := ic.ClusterDomain()
response, err := client.ListPrivateZonesByName(zoneName)
if err != nil {
allErrs = append(allErrs, field.InternalError(namePath, err))
}
for _, zone := range response.Zones.Zone {
if zone.ZoneName == zoneName {
allErrs = append(allErrs, field.Invalid(namePath, ic.ObjectMeta.Name, fmt.Sprintf("cluster name is unavailable, private zone name %s already exists", zoneName)))
break
}
}
return allErrs
}
func validateNatGateway(client *Client, ic *types.InstallConfig) field.ErrorList {
allErrs := field.ErrorList{}
regionPath := field.NewPath("platform").Child("alibabacloud").Child("region")
natGatewayZones, err := client.ListEnhanhcedNatGatewayAvailableZones()
if err != nil {
return append(allErrs, field.InternalError(regionPath, err))
}
if len(natGatewayZones.Zones) == 0 {
allErrs = append(allErrs, field.Invalid(regionPath, ic.Platform.AlibabaCloud.Region, "enhanced NAT gateway is not supported in the current region"))
}
return allErrs
}
type mergedMachinePool struct {
alibabacloudtypes.MachinePool
zonesFieldPath *field.Path
instanceTypeFieldPath *field.Path
}
func (a *mergedMachinePool) setWithFieldPath(required *alibabacloudtypes.MachinePool, fldPath *field.Path) {
if required == nil || a == nil {
return
}
if len(required.Zones) > 0 {
a.Zones = required.Zones
a.zonesFieldPath = fldPath.Child("zones")
}
if required.InstanceType != "" {
a.InstanceType = required.InstanceType
a.instanceTypeFieldPath = fldPath.Child("instanceType")
}
}
|
package main
import "fmt"
func main() {
if 7%5 == 0 { //if 7 is divisible by 5
fmt.Println("buset bg")
} else { //penulisan else di golang harus 1line setelah tutup if{}
fmt.Println("kayae tidak mungkin. males mau jabarin")
}
if 10+10 == 20 {
// check color formating...
// buset..
// digolang statment + () malah jadi kek fungsi :/
// meski statement tetep worksih
fmt.Println("adalah benar")
}
if (10 + 10) == 20 {
fmt.Println("juga sama benarnya")
}
if false {
fmt.Println("lanjut else if bawahnya yaa")
} else if true {
fmt.Println("mantap ketemu dengan saya disini")
} else {
fmt.Println("tidak akan pernah bertemu dengan saya")
}
if num := 9; num < 0 { //mirip dengan requirement and
fmt.Println("tidak akan muncul karena salah")
}
if num := 9; num == 9 {
fmt.Println("alternative. dan akan muncul karena benar")
}
}
|
package inform
import (
// Standard library
"io/ioutil"
"net/http"
"net/url"
"strings"
// Third-party packages
"github.com/pkg/errors"
)
// Options represent user-configurable values, which are used in processing commands
// and formatting output.
type Options struct {
Prefix string
}
// Default values for options, as assigned to newly created Author instances.
var defaultOptions = Options{
Prefix: "?",
}
type Author struct {
ID string
Options Options
Stories []*Story
}
func (a *Author) GetStory(name string) (*Story, error) {
if name == "" {
return nil, errors.New("story name is empty")
}
for i := range a.Stories {
if a.Stories[i].Name == name {
return a.Stories[i], nil
}
}
return nil, errors.New("no story found with name '" + name + "'")
}
func (a *Author) AddStory(name, path string) (*Story, error) {
var story *Story
if name == "" {
return nil, errors.New("story name is empty")
} else if s, _ := a.GetStory(name); s != nil {
story = s
} else if u, err := url.Parse(path); err != nil || (u.Scheme != "https" && u.Scheme != "http") {
return nil, errors.New("location given is not a valid HTTP URL")
}
resp, err := http.Get(path)
if err != nil {
return nil, errors.New("could not fetch story file from URL given")
}
defer resp.Body.Close()
if body, err := ioutil.ReadAll(resp.Body); err != nil {
return nil, errors.New("could not fetch story file from URL given")
} else if story == nil {
story = NewStory(name, a.ID).WithSource(body)
a.Stories = append(a.Stories, story)
} else {
story.WithSource(body)
}
return story, nil
}
func (a *Author) RemoveStory(name string) error {
if name == "" {
return errors.New("story name is empty")
}
// Find story with given name, and remove from list assigned to author.
for i := range a.Stories {
if a.Stories[i].Name == name {
a.Stories = append(a.Stories[:i], a.Stories[i+1:]...)
return nil
}
}
return errors.New("no story found with name '" + name + "'")
}
func (a *Author) SetOption(name, value string) error {
switch strings.ToLower(name) {
case "prefix":
if value == "" {
return errors.New("cannot set empty prefix value")
}
a.Options.Prefix = value
default:
return errors.New("option name '" + name + "' is unknown")
}
return nil
}
func NewAuthor(id string) *Author {
return &Author{ID: id, Options: defaultOptions}
}
|
package message
const (
InvalidRequest = "Invalid Request."
SomethingWrong = "Something Went Wrong. Please try again."
EmailInUse = "email address already in use"
EmailNotRegistered = "Email is not registered with us."
TokenIsNotValid = "Token is invalid."
TokenIsExpired = "Token is expired."
InActive = "Your account has been deactivated."
InvalidCredential = "Invalid Credentials"
UserNotFoundByToken = "User not found"
)
|
package ttlcache
import (
"fmt"
"math/rand"
"testing"
"time"
)
func TestCleanupLatency(t *testing.T) {
t.Run("100kv", func(t *testing.T) {
cache := NewCache(0)
for _, kv := range genKV(100) {
cache.Set(kv[0], kv[1])
}
time.Sleep(1100 * time.Millisecond)
now := time.Now()
cache.Cleanup()
fmt.Printf("delete 100kv\tlatency: %v\n", time.Since(now))
if cache.Len() != 0 {
t.Error("cache should be cleanup")
}
})
t.Run("1000kv", func(t *testing.T) {
cache := NewCache(0)
for _, kv := range genKV(1000) {
cache.Set(kv[0], kv[1])
}
time.Sleep(1100 * time.Millisecond)
now := time.Now()
cache.Cleanup()
fmt.Printf("delete 1000kv\tlatency: %v\n", time.Since(now))
if cache.Len() != 0 {
t.Error("cache should be cleanup")
}
})
t.Run("10000kv", func(t *testing.T) {
cache := NewCache(0)
for _, kv := range genKV(10000) {
cache.Set(kv[0], kv[1])
}
time.Sleep(1100 * time.Millisecond)
now := time.Now()
cache.Cleanup()
fmt.Printf("delete 10000kv\tlatency: %v\n", time.Since(now))
if cache.Len() != 0 {
t.Error("cache should be cleanup")
}
})
t.Run("100000kv", func(t *testing.T) {
cache := NewCache(0)
for _, kv := range genKV(100000) {
cache.Set(kv[0], kv[1])
}
time.Sleep(1100 * time.Millisecond)
now := time.Now()
cache.Cleanup()
fmt.Printf("delete 100000kv\tlatency: %v\n", time.Since(now))
if cache.Len() != 0 {
t.Error("cache should be cleanup")
}
})
}
func TestCacheLen(t *testing.T) {
cache := NewCache(time.Second)
cache.Set("foo", "bar")
if cache.Len() != 1 {
t.Error("len should be 1")
}
time.Sleep(1100 * time.Millisecond)
_, ok := cache.Get("foo")
if ok {
t.Error("key should be expired")
}
if cache.Len() != 0 {
t.Error("len should be 0")
}
}
func BenchmarkCache(b *testing.B) {
kvs := genKV(100000)
cache := NewCache(time.Hour)
// -------- 1000kv ----------
n := 1000
for i := 0; i < n; i++ {
cache.Set(kvs[i][0], kvs[i][1])
}
if cache.Len() != n {
b.FailNow()
}
b.Run("1000kv Set", func(b *testing.B) {
for i := 0; i < b.N; i++ {
cache.Set(kvs[0][0], kvs[0][1])
}
})
b.Run("1000kv Get", func(b *testing.B) {
for i := 0; i < b.N; i++ {
cache.Get(kvs[0][0])
}
})
fmt.Println()
// ---------- 10000 kv --------------
n = 10000
for i := 0; i < n; i++ {
cache.Set(kvs[i][0], kvs[i][1])
}
if cache.Len() != n {
b.FailNow()
}
b.Run("10000kv Set", func(b *testing.B) {
for i := 0; i < b.N; i++ {
cache.Set(kvs[0][0], kvs[0][1])
}
})
b.Run("10000kv Get", func(b *testing.B) {
for i := 0; i < b.N; i++ {
cache.Get(kvs[0][0])
}
})
fmt.Println()
// ---------- 100000 kv ------------
n = 100000
for i := 0; i < n; i++ {
cache.Set(kvs[i][0], kvs[i][1])
}
if cache.Len() != n {
b.FailNow()
}
b.Run("100000kv Set", func(b *testing.B) {
for i := 0; i < b.N; i++ {
cache.Set(kvs[0][0], kvs[0][1])
}
})
b.Run("100000kv Get", func(b *testing.B) {
for i := 0; i < b.N; i++ {
cache.Get(kvs[0][0])
}
})
}
func genKV(n int) [][2]string {
kvs := make([][2]string, n)
for i := 0; i < n; i++ {
kvs[i][0], kvs[i][1] = randStr(20), randStr(15)
}
return kvs
}
func randStr(n int) string {
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
rand.Seed(time.Now().UnixNano())
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
|
package tail
import (
"bufio"
"context"
"log"
"os"
"sync"
"github.com/marcsauter/rtail/pkg/pb"
)
// Tailer interface
type Tailer interface {
File(context.Context, *pb.FileRequest)
}
// tail
type tail struct {
sync.Mutex
wg *sync.WaitGroup
stream pb.Proxy_RegisterClient
}
// New returns a new Tailer
func New(wg *sync.WaitGroup, stream pb.Proxy_RegisterClient) Tailer {
return &tail{
wg: wg,
stream: stream,
}
}
// send serializes send operation on gRPC stream
func (t *tail) send(line *pb.Line) error {
t.Lock()
defer t.Unlock()
return t.stream.Send(&pb.AgentMessage{
Line: line,
})
}
// File tail a file
func (t *tail) File(ctx context.Context, r *pb.FileRequest) {
t.wg.Add(1)
go func() {
defer t.wg.Done()
f, _ := os.Open(r.Path)
defer f.Close()
scanner := bufio.NewScanner(f)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
if err := t.send(&pb.Line{
Line: scanner.Text(),
Key: r.Key,
}); err != nil {
log.Printf("send failed: %v", err)
return
}
}
if err := scanner.Err(); err != nil {
log.Printf("reading %s failed: %v", r.Path, err)
}
if err := t.send(&pb.Line{
Eof: true,
Key: r.Key,
}); err != nil {
log.Printf("send failed: %v", err)
return
}
}()
}
|
package lib
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"net/url"
)
// Google Maps API reference on reverse geocoding.
// https://developers.google.com/maps/documentation/geocoding/#ReverseGeocoding
const (
MAP_API_URL = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false"
MAP_Q_URL = "http://maps.google.com/"
)
type LatLng map[string]float64
func MapLink(address string, name string) string {
if len(name) != 0 {
address = fmt.Sprintf("%v (%v)", address, name)
}
return fmt.Sprintf("%v?q=%v", MAP_Q_URL, url.QueryEscape(address))
}
func Geocode(address string) (LatLng, error) {
url := fmt.Sprintf("%v&address=%v", MAP_API_URL, url.QueryEscape(address))
_, ll := queryGMaps(url)
return ll, nil
}
func ReverseGeocode(ll LatLng) (string, error) {
if len(ll) != 2 {
return "", errors.New("Incorrectly formatted LatLng coordinates.")
}
url := fmt.Sprintf("%s&latlng=%v,%v", MAP_API_URL, ll["lat"], ll["lng"])
address, _ := queryGMaps(url)
return address, nil
}
// Structs to contain the JSON response from Google Maps.
type MapsResult struct {
Formatted_address string
// Geometry contains more than just LatLng coords, but that's all we care about.
Geometry map[string]LatLng
}
type MapsMessage struct {
Status string
Results []MapsResult
}
func queryGMaps(url string) (string, LatLng) {
resp, err := http.Get(url)
if err != nil {
log.Println("Failed to query google maps.", err.Error())
return "", nil
}
defer resp.Body.Close()
var m MapsMessage
dec := json.NewDecoder(resp.Body)
dec.Decode(&m)
if m.Status != "OK" {
log.Println("Failed to decode message from Maps API.")
return "", nil
}
address := m.Results[0].Formatted_address
ll := m.Results[0].Geometry["location"]
return address, ll
}
|
package main
import (
post "actions/post"
"cp"
"da"
"log"
"routes"
"github.com/hjin-me/banana"
)
func main() {
ctx := banana.App()
log.Println("server started")
cfg, ok := ctx.Value("cfg").(banana.AppCfg)
if !ok {
log.Fatalln("configuration not ok")
}
dsnRaw, ok := cfg.Env.Db["mysql"]
if !ok {
log.Fatalln("mysql conf not exits")
}
dsn, ok := dsnRaw.(string)
if !ok {
log.Fatalln("mysql dsn not ok")
}
err := da.Create(dsn)
if err != nil {
log.Fatalln(err)
}
defer da.Close()
log.Println("database connected")
routes.Reg("post_page", post.Read)
routes.Reg("archives_page", post.Query)
routes.Reg("home_page", post.Latest)
routes.Reg("category_page", post.Category)
routes.Reg("login_page", cp.LoginPage)
routes.Reg("login_post", cp.Login)
routes.Reg("admin_users_page", cp.Users)
routes.Reg("admin_user_page", cp.UsersCreatePage)
routes.Reg("admin_user_post", cp.UsersCreate)
routes.Reg("admin_posts_page", cp.Posts)
routes.Reg("admin_post_new_page", cp.NewPost)
routes.Reg("admin_post_edit_page", cp.Post)
routes.Reg("admin_post_new_post", cp.SaveNewPost)
routes.Reg("admin_post_edit_post", cp.SavePost)
routes.Reg("admin_dashboard_page", cp.DashBoard)
log.Println("route complete")
banana.File("/static", cfg.Env.Statics)
routes.Handle()
// route init
<-ctx.Done()
}
|
package fileversion
import "github.com/scjalliance/drivestream/resource"
// Reference is a file version reference.
type Reference interface {
// File returns the ID of the file.
File() resource.ID
// Version returns the version number of the file.
Version() resource.Version
// Create creates a new file version with the given version number
// and data. If a version already exists with the version number an
// error will be returned.
Create(data resource.FileData) error
// Data returns the data of the file version.
Data() (resource.FileData, error)
}
|
package dbinitializer
import (
"database/sql"
"fmt"
"log"
"github.com/kenigbolo/go-web-app/model"
_ "github.com/lib/pq" // Database initializer
)
// ConnectToDatabase function
func ConnectToDatabase() *sql.DB {
db, err := sql.Open("postgres", "postgres://postgres:postgres@localhost/go_web_app?sslmode=disable")
if err != nil {
log.Fatalln(fmt.Errorf("Unable to connect to database: %v", err))
}
model.SetDatabase(db)
return db
}
|
package models
type Project struct {
name string
criteria Criteria
}
//docAddress表示项目文件地址
//proAddress表示项目地址
type CreateProjectResult struct {
DocAddress interface{}
ProAddress interface{}
} |
// Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package driver
import (
"context"
"testing"
"time"
"github.com/pingcap/failpoint"
"github.com/pingcap/tidb/session"
"github.com/pingcap/tidb/util"
"github.com/stretchr/testify/require"
)
func TestFailBusyServerCop(t *testing.T) {
store, _ := createTestStore(t)
se, err := session.CreateSession4Test(store)
require.NoError(t, err)
var wg util.WaitGroupWrapper
require.NoError(t, failpoint.Enable("tikvclient/rpcServerBusy", `return(true)`))
wg.Run(func() {
time.Sleep(time.Millisecond * 100)
require.NoError(t, failpoint.Disable("tikvclient/rpcServerBusy"))
})
wg.Run(func() {
rs, err := se.Execute(context.Background(), `SELECT variable_value FROM mysql.tidb WHERE variable_name="bootstrapped"`)
if len(rs) > 0 {
defer func() {
require.NoError(t, rs[0].Close())
}()
}
require.NoError(t, err)
req := rs[0].NewChunk(nil)
err = rs[0].Next(context.Background(), req)
require.NoError(t, err)
require.NotEqual(t, 0, req.NumRows())
require.Equal(t, "True", req.GetRow(0).GetString(0))
})
wg.Wait()
}
|
package state
func (state *luaState) GetTop() int {
return state.stack.top
}
func (state *luaState) AbsIndex(idx int) int {
return state.stack.absIndex(idx)
}
func (state *luaState) CheckStack(n int) bool {
state.stack.check(n)
return true
}
func (state *luaState) Pop(n int) {
for i := 0; i < n; i++ {
state.stack.pop()
}
}
func (state *luaState) Copy(fromIdx, toIdx int) {
val := state.stack.get(fromIdx)
state.stack.set(toIdx, val)
}
func (state *luaState) PushValue(idx int) {
val := state.stack.get(idx)
state.stack.push(val)
}
func (state *luaState) Replace(idx int) {
val := state.stack.pop()
state.stack.set(idx, val)
}
func (state *luaState) Rotate(idx, n int) {
t := state.stack.top - 1
p := state.AbsIndex(idx) - 1
var m int
if n >= 0 {
m = t - n
} else {
m = p - n - 1
}
state.stack.reverse(p, m)
state.stack.reverse(m+1, t)
state.stack.reverse(p, t)
}
func (state *luaState) Insert(idx int) {
state.Rotate(idx, 1)
}
func (state *luaState) Remove(idx int) {
state.Rotate(idx, -1)
state.Pop(1)
}
func (state *luaState) SetTop(idx int) {
newTop := state.stack.absIndex(idx)
if newTop < 0 {
panic("stack underflow!")
}
n := state.stack.top - newTop
if n > 0 {
for i := 0; i < n; i++ {
state.stack.pop()
}
} else if n < 0 {
for i := 0; i > n; i-- {
state.stack.push(nil)
}
}
}
|
package cryptutil
import (
"crypto/hmac"
"crypto/sha512"
"golang.org/x/crypto/bcrypt"
"google.golang.org/protobuf/proto"
)
// Hash generates a hash of data using HMAC-SHA-512/256. The tag is intended to
// be a natural-language string describing the purpose of the hash, such as
// "hash file for lookup key" or "master secret to client secret". It serves
// as an HMAC "key" and ensures that different purposes will have different
// hash output. This function is NOT suitable for hashing passwords.
func Hash(tag string, data []byte) []byte {
h := hmac.New(sha512.New512_256, []byte(tag))
h.Write(data)
return h.Sum(nil)
}
// HashPassword generates a bcrypt hash of the password using work factor 14.
func HashPassword(password []byte) ([]byte, error) {
return bcrypt.GenerateFromPassword(password, 14)
}
// CheckPasswordHash securely compares a bcrypt hashed password with its possible
// plaintext equivalent. Returns nil on success, or an error on failure.
func CheckPasswordHash(hash, password []byte) error {
return bcrypt.CompareHashAndPassword(hash, password)
}
// HashProto hashes a protobuf message. It sets `Deterministic` to true to ensure
// the encoded message is always the same. (ie map order is lexographic)
func HashProto(msg proto.Message) []byte {
opts := proto.MarshalOptions{
AllowPartial: true,
Deterministic: true,
}
bs, _ := opts.Marshal(msg)
return Hash("proto", bs)
}
|
package utils
import (
"net/http"
"strings"
tr "github.com/ebikode/eLearning-core/translation"
"github.com/go-sql-driver/mysql"
)
const (
// ER_DUP_ENTRY
ER_DUP_ENTRY = 1062
AdminStaffID = "uix_admins_staff_id"
AdminPhone = "uix_admins_phone"
AdminEmail = "uix_admins_email"
AccountPhone = "uix_accounts_phone"
AccountEmail = "uix_accounts_email"
CustomerUsername = "uix_customers_username"
CustomerPhone = "uix_customers_phone"
CustomerEmail = "uix_customers_email"
SearchPlanName = "uix_categories_name"
SearchPlanLangKey = "uix_categories_lang_key"
AppSettingName = "uix_app_settings_name"
AppSettingKey = "uix_app_settings_s_key"
)
// UniqueDuplicateError - encapsulates database duplication error
type UniqueDuplicateError struct {
Key string // Translation key
Request *http.Request
}
func (e *UniqueDuplicateError) Error() string {
field := Translate(tr.TParam{Key: e.Key, TemplateData: nil, PluralCount: nil}, e.Request)
errorMsg := Translate(
tr.TParam{
Key: "validation.unique",
TemplateData: map[string]interface{}{"Field": field},
PluralCount: nil,
}, e.Request)
return errorMsg
}
// isUniqueConstraintError Check unique constraint
func isUniqueConstraintError(err error, constraintName string) bool {
if mysqlErr, ok := err.(*mysql.MySQLError); ok {
containsString := strings.Contains(err.Error(), constraintName)
return mysqlErr.Number == ER_DUP_ENTRY && containsString
}
return false
}
// CheckUniqueError Check DB conraint error
func CheckUniqueError(r *http.Request, err error) error {
if isUniqueConstraintError(err, AdminEmail) || isUniqueConstraintError(err, CustomerEmail) ||
isUniqueConstraintError(err, AccountEmail) {
return &UniqueDuplicateError{Key: "general.email", Request: r}
}
if isUniqueConstraintError(err, AdminPhone) || isUniqueConstraintError(err, CustomerPhone) ||
isUniqueConstraintError(err, AccountPhone) {
return &UniqueDuplicateError{Key: "general.phone", Request: r}
}
if isUniqueConstraintError(err, AdminStaffID) {
return &UniqueDuplicateError{Key: "general.staff_id", Request: r}
}
if isUniqueConstraintError(err, CustomerUsername) {
return &UniqueDuplicateError{Key: "general.username", Request: r}
}
if isUniqueConstraintError(err, SearchPlanName) ||
isUniqueConstraintError(err, AppSettingName) {
return &UniqueDuplicateError{Key: "general.name", Request: r}
}
if isUniqueConstraintError(err, AppSettingKey) {
return &UniqueDuplicateError{Key: "general.key", Request: r}
}
return nil
}
|
package model
import (
"time"
)
type BaseModel struct {
ID int `gorm:"column:id;primary_key" json:"id"`
CreatedAt time.Time `gorm:"column:created_at" json:"created_at"`
UpdatedAt time.Time `gorm:"column:updated_at" sql:"index" json:"updated_at"`
DeletedAt *time.Time `gorm:"column:deleted_at" sql:"index" json:"deleted_at"`
}
|
// Copyright (c) Facebook, Inc. and its affiliates.
// All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
package main
import (
"fmt"
"github.com/davecgh/go-spew/spew"
"github.com/facebookexperimental/GOAR/tailerhandler"
"github.com/golang/glog"
"github.com/streadway/amqp"
syslog "gopkg.in/mcuadros/go-syslog.v2"
)
// SyslogTailer represents a tailer that reads syslog events from a syslog stream channel
type SyslogTailer struct {
SyslogStream syslog.LogPartsChannel
PublishEndpoint tailerhandler.SyslogTailerQueue
}
// Tail reads data from a Syslog Channel line by line and pushes them out to external queue/component
func (tailer *SyslogTailer) Tail() error {
glog.Infof("Syslog host tailer waiting for lines...")
for logParts := range tailer.SyslogStream {
if glog.V(2) {
glog.Infof("Syslog received: %v", spew.Sdump(logParts))
}
if err := tailer.publish(tailerhandler.Event(fmt.Sprint(logParts))); err != nil {
glog.Errorf("Error publishing Event to an external queue, %s", err)
}
}
return nil
}
// publish pushes event to a remote outgoing queue
func (tailer *SyslogTailer) publish(event tailerhandler.Event) error {
err := tailer.PublishEndpoint.Channel.Publish(
"", // exchange
tailer.PublishEndpoint.OutQueue.Name, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "text/plain",
Body: event,
})
return err
}
|
package controller
import (
"model"
"appengine"
"net/http"
"html/template"
)
var transactionsTmpl = template.Must(template.ParseFiles("templates/transactions.html"))
func transactions(c appengine.Context, w http.ResponseWriter, r *http.Request) error {
budget, err := model.CurrentBudget(c)
if err != nil {
http.Redirect(w, r, "/budget", http.StatusTemporaryRedirect)
return nil
}
// Query the database for all transactions
transactions, err := model.QueryTransactions(c, budget)
if err != nil {
return err
}
categories, err := model.QueryCategories(c, budget)
if err != nil {
return err
}
// Render the results to the user
if err := WriteHeader(w, "Transactions"); err != nil {
return err
}
data := map[string]interface{}{
"transactions": transactions,
"categories": categories,
}
if err := transactionsTmpl.Execute(w, data); err != nil {
return err
}
if err := WriteFooter(w); err != nil {
return err
}
return nil
}
func createTransaction(c appengine.Context, w http.ResponseWriter, r *http.Request) error {
budget, err := model.CurrentBudget(c)
if err != nil {
return err
}
transaction, err := model.CreateTransaction(c, r, budget)
if err != nil {
return err
}
if err := transaction.Commit(c); err != nil {
return err
}
http.Redirect(w, r, "/transactions", http.StatusFound)
return nil
}
func deleteTransaction(c appengine.Context, w http.ResponseWriter, r *http.Request) error {
budget, err := model.CurrentBudget(c)
if err != nil {
return err
}
if err := model.DeleteTransaction(c, r, budget); err != nil {
return err
}
http.Redirect(w, r, "/transactions", http.StatusFound)
return nil
}
|
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/urfave/cli/v2"
"golang.org/x/crypto/pbkdf2"
)
type Paste struct {
Paste struct {
Name struct {
Data string `json:"data"`
Iv string `json:"iv"`
Salt string `json:"salt"`
} `json:"name"`
Body struct {
Data string `json:"data"`
Iv string `json:"iv"`
Salt string `json:"salt"`
} `json:"body"`
} `json:"paste"`
Files []Files `json:"files"`
SourceCode bool `json:"sourceCode"`
SelfDestruct bool `json:"selfDestruct"`
ExpiresMinutes int64 `json:"expiresMinutes"`
}
type Files struct {
Name struct {
Data string `json:"data"`
Vector string `json:"iv"`
Salt string `json:"salt"`
} `json:"name"`
Content struct {
Data string `json:"data"`
Vector string `json:"iv"`
Salt string `json:"salt"`
} `json:"content"`
}
type PasteSuccess struct {
Msg string `json:"msg"`
Paste struct {
Uuid string `json:"uuid"`
} `json:"paste"`
}
func main() {
app := cli.NewApp()
app.Name = "Paste.me"
app.Version = "v0.1"
app.Usage = "Share your pastes securely"
app.Flags = []cli.Flag{
&cli.StringSliceFlag{
Name: "file",
Usage: "One or more files to attach to the paste. If you want to attach more than one file, use --file more times!",
},
&cli.StringFlag{
Name: "name",
Usage: "Insert the name of the paste here.",
Required: true,
},
&cli.StringFlag{
Name: "body",
Usage: "Here you can insert the paste body or send it through cli.",
Required: true,
},
&cli.Int64Flag{
Name: "expires",
Usage: "Here you will be able to set an expiration time for your pastes. The expiration time should be defined in minutes. Allowed values for the time being: 5,10,60,1440,10080,43800.",
},
&cli.BoolFlag{
Name: "destroy",
Usage: "With this flag, you are posting the paste with a 'Self Destruct' flag. The link will work only once.",
},
&cli.BoolFlag{
Name: "source",
Usage: "With this flag, you are posting a paste which is some kind of source code. Syntax highlighting will be applied.",
},
}
app.Action = Action
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
func Action(c *cli.Context) error {
var err error
name := c.String("name")
sourceCode := c.Bool("source")
destroy := c.Bool("destroy")
body := c.String("body")
expires := c.Int64("expires")
files := c.StringSlice("file")
pasteText := ""
if len(name) == 0 {
fmt.Println("Please provide a name for your paste. Use the --help if in doubt.")
return errors.New("paste_name_error")
}
var terminalText string
stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) == 0 {
terminalText, err = ReadDataFromTerminal(os.Stdin)
if err != nil {
return err
}
} else {
if len(body) > 0 {
terminalText, err = ReadDataFromTerminal(strings.NewReader(body))
} else {
terminalText = ""
}
}
if len(terminalText) > 0 {
pasteText = terminalText
} else {
pasteText = body
}
if err != nil || len(pasteText) == 0 {
fmt.Println("Your paste has a length of 0. Try again, but this time try to put some content.")
return errors.New("paste_length_error")
}
// if destroy is set, pass a valid expires to the paste
// the paste will still self-destruct, this is so we are
// on par with the WEB UI
if destroy {
expires = 60 // expires is not considered for self-destruct pastes
}
if !destroy && !IsValidMinutes(expires) {
fmt.Println("You did not provide a valid expires flag. See --help for more insight on this one.")
return errors.New("expires_not_found")
}
rb, err := GenerateRandomBytes(28)
if err != nil {
fmt.Println("Not enough entropy for random bytes! Please try again!")
os.Exit(1)
}
//rand.Read(rb)
h := sha256.New()
h.Write(rb)
passPhrase := hex.EncodeToString(h.Sum(nil))
encryptName := encrypt(passPhrase, []byte(name))
encryptData := encrypt(passPhrase, []byte(pasteText))
splittedEncryptName := strings.Split(encryptName, "-")
splittedEncryptData := strings.Split(encryptData, "-")
//split encrypt result
paste := &Paste{}
paste.Paste.Name.Data = splittedEncryptName[2]
paste.Paste.Name.Iv = splittedEncryptName[1]
paste.Paste.Name.Salt = splittedEncryptName[0]
paste.Paste.Body.Data = splittedEncryptData[2]
paste.Paste.Body.Iv = splittedEncryptData[1]
paste.Paste.Body.Salt = splittedEncryptData[0]
paste.SourceCode = sourceCode
paste.SelfDestruct = destroy
// Note: The cli client does not support sending files yet!
// process the files if any
paste.Files = ProcessFiles(files, passPhrase)
if !destroy {
paste.ExpiresMinutes = expires
}
jsonValue, _ := json.Marshal(paste)
req, err := http.NewRequest("POST", "https://api.paste.me/api/paste/new", bytes.NewBuffer(jsonValue))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
bodyBytes, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return cli.NewExitError("There was some problem while sending the paste data. Please try again later or contact the site administrator.", 15)
}
if resp.StatusCode == 200 {
res := PasteSuccess{}
err = json.Unmarshal(bodyBytes, &res)
if err != nil {
return cli.NewExitError("We received an invalid response from the server. Please contact the site administrator.", 16)
}
msg := `Paste added successfully!
Share this url to your friends: https://paste.me/paste/` + res.Paste.Uuid + `#` + passPhrase
fmt.Println(msg)
return nil
} else {
return cli.NewExitError("There was some error while pasting your data. Please try again later or contact the Paste.me admin!", 17)
}
return nil
}
// @SRC: https://gist.github.com/dopey/c69559607800d2f2f90b1b1ed4e550fb
// GenerateRandomBytes returns securely generated random bytes.
// It will return an error if the system's secure random
// number generator fails to function correctly, in which
// case the caller should not continue.
func GenerateRandomBytes(n int) ([]byte, error) {
b := make([]byte, n)
_, err := rand.Read(b)
// Note that err == nil only if we read len(b) bytes.
if err != nil {
return nil, err
}
return b, nil
}
func ReadDataFromTerminal(r io.Reader) (string, error) {
var result string
rBytes, err := ioutil.ReadAll(r)
if err != nil {
return "", err
}
result = string(rBytes)
return result, nil
}
// @SRC: https://gist.github.com/tscholl2/dc7dc15dc132ea70a98e8542fefffa28
func deriveKey(passPhrase string, salt []byte) ([]byte, []byte) {
if salt == nil {
salt = make([]byte, 8)
// http://www.ietf.org/rfc/rfc2898.txt
// Salt.
rand.Read(salt)
}
return pbkdf2.Key([]byte(passPhrase), salt, 1000, 32, sha256.New), salt
}
// @SRC: https://gist.github.com/tscholl2/dc7dc15dc132ea70a98e8542fefffa28
func encrypt(passphrase string, plaintext []byte) string {
key, salt := deriveKey(passphrase, nil)
iv := make([]byte, 12)
// http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf
// Section 8.2
rand.Read(iv)
b, _ := aes.NewCipher(key)
aesgcm, _ := cipher.NewGCM(b)
data := aesgcm.Seal(nil, iv, plaintext, nil)
return hex.EncodeToString(salt) + "-" + hex.EncodeToString(iv) + "-" + hex.EncodeToString(data)
}
func IsValidMinutes(minutes int64) bool {
switch minutes {
case
5, 10, 60, 1440, 10080, 43800:
return true
}
return false
}
func ProcessFiles(files []string, passPhrase string) []Files {
var postFiles []Files
for _, file := range files {
if exists := CheckIfFileExists(file); exists == true {
encryptFileName := encrypt(passPhrase, []byte(filepath.Base(file)))
fileNameSplitted := strings.Split(encryptFileName, "-")
encryptFileContent := encrypt(passPhrase, ReadFile(file))
encryptFileContentSplitted := strings.Split(encryptFileContent, "-")
postFile := Files{}
postFile.Name.Data = fileNameSplitted[2]
postFile.Name.Vector = fileNameSplitted[1]
postFile.Name.Salt = fileNameSplitted[0]
postFile.Content.Data = encryptFileContentSplitted[2]
postFile.Content.Vector = encryptFileContentSplitted[1]
postFile.Content.Salt = encryptFileContentSplitted[0]
postFiles = append(postFiles, postFile)
} else {
fmt.Printf("The file %s either does not exist or is a directory! Please provide a correct path!\n", file)
os.Exit(1)
}
}
return postFiles
}
// Check if file exists and it is not a directory...
func CheckIfFileExists(path string) bool {
fileInfo, err := os.Stat(path)
if os.IsNotExist(err) {
return false
}
return !fileInfo.IsDir()
}
func ReadFile(path string) []byte {
dat, err := ioutil.ReadFile(path)
if err != nil {
fmt.Printf("There was an error while reading the file! %s => %v\n", path, err)
os.Exit(1)
}
return dat
}
|
package problem0039
import "testing"
func TestCombininationSum(t *testing.T) {
t.Log(combinationSum([]int{2, 3, 6, 7}, 7))
t.Log(combinationSum([]int{2, 3, 5}, 8))
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.