text
stringlengths
11
4.05M
package router import ( "github.com/gin-gonic/gin" "github.com/jiujuanfeng/yunheblog/controller/admin" "github.com/jiujuanfeng/yunheblog/utils" "html/template" ) func Route(router *gin.Engine) { funcMap := template.FuncMap{ "dateFormat" : utils.DateFormat, } router.SetFuncMap(funcM...
package main import ( "log" "os" "gopkg.in/h2non/filetype.v1" ) func isVideo(filename string) bool { file, _ := os.Open(filename) defer file.Close() // First 261 bytes suffice header := make([]byte, 261) if _, err := file.Read(header); err != nil { log.Fatal(err) } return fil...
package handlers import "net/http" // middleware handler for supporting Cross Origin Requests type CORSHandler struct { Handler http.Handler } // returns a new CORSHandler middleware handler func NewCorsHandler(destHandler http.Handler) *CORSHandler { return &CORSHandler{destHandler} } // adds various headers to ...
package main import "fmt" func getMinlength(arr []int) int { if len(arr) < 2 { return 0 } noMinIndex := -1 min := arr[len(arr)-1] for i := len(arr) - 2; i > -1; i-- { if arr[i] > min { noMinIndex = i } else { min = min1(min, arr[i]) } } if noMinIndex == -1 { return 0 } noMaxIndex := -1 max ...
package cronJob import "github.com/gorhill/cronexpr" type CronJob struct { // 定时任务名 Name string `json:"name"` // 具体执行的命令 Cmd string `json:"cmd"` // 执行规则 CronExpr string `json:"cron_expr"` //CronExpr *cronexpr.Expression `json:"cron_expr"` // 启用 cronexpr.Expression 类型,这完全依赖"github.com/gorhill/cronexpr" } fun...
package dict import ( "testing" ) func TestDictLoad(t *testing.T) { d := NewDict(DefaultDictPath) err := d.Load() if err != nil { t.Error("Load dict failed") } if d.Size() <= 0 { t.Error("Dict is empty") } } func TestDefaultDictLoad(t *testing.T) { d := NewDefaultDict() err := d.Load() if err != nil { ...
package routes import ( "github.com/kataras/iris/v12" ) func registerPathParamRoute(app *iris.Application) { // Method: GET // Resource: http://localhost:8080/user/42 // // Need to use a custom regexp instead? // Easy; // Just mark the parameter's type to 'string' // which accepts anything and make use o...
package cards import ( "math/rand" "fmt" ) type Deck struct { data []byte index int } func ShuffledDeck() *Deck { data := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45,...
package main import ( "fmt" ) func main() { num01 := 123 var num02 int = 1234567890 // ↑int型を宣言 num03 := 1.23 // ↑データ型を省略 var num04 float64 = 1.23456789 // ↑float64型を宣言 fmt.Println(num01) fmt.Println(num02) fmt.Println(num03) fmt.Println(num04) }
package genre import ( . "movie-app/entity" "gorm.io/gorm" ) type Repository interface { FindAll() ([]Genre, error) FindById(id int) (Genre, error) Save(genre Genre) (Genre, error) Update(genre Genre) (Genre, error) Delete(genre Genre) (bool, error) } type repository struct { db *gorm.DB } func NewGenreRep...
package model import ( "context" "encoding/json" "gamesvr/manager" "math" "shared/common" "shared/csv/static" "shared/protobuf/pb" "shared/statistic/logreason" "shared/utility/coordinate" "shared/utility/errors" "shared/utility/glog" "shared/utility/number" ) const ( searchBlackMaxLoop = 10000 Yggdrasi...
package util import ( "encoding/base64" "encoding/binary" "fmt" "math/rand" "testing" ) func TestMD5(t *testing.T) { //fmt.Printf("%x \n", 0x23a&0x0f/0x1) // //fmt.Print(23 / 5,23%5) // //return //var ( // in = "1" // expected = "c4ca4238a0b923820dcc509a6f75849b" //) //actual := MD5(in) //if a...
package main import ( "fmt" "log" "os" "github.com/kayac/ecspresso" config "github.com/kayac/go-config" kingpin "gopkg.in/alecthomas/kingpin.v2" ) var Version = "current" func main() { os.Exit(_main()) } func _main() int { kingpin.Command("version", "show version") conf := kingpin.Flag("config", "config ...
package main import ( "github.com/astaxie/beego" "github.com/astaxie/beego/logs" _ "homework/backend/middleware" _ "homework/backend/routers" "os" "os/exec" "path/filepath" ) func GetAPPRootPath() string { file, err := exec.LookPath(os.Args[0]) if err != nil { return "" } p, err := filepath.Abs(file) if...
package requests import ( "encoding/json" "io/ioutil" "net/http" "net/url" "github.com/atomicjolt/canvasapi" "github.com/atomicjolt/canvasapi/models" ) // ListPlannerOverrides Retrieve a planner override for the current user // https://canvas.instructure.com/doc/api/planner.html // type ListPlannerOverrides st...
package cubemap import ( "github.com/go-gl/mathgl/mgl32" ) type CubemapSample struct { Origin mgl32.Vec3 Size byte AlignmentPadding [3]byte }
package main import ( // "encoding/json" "fmt" "github.com/dtoebe/menucli/externalhub" ) func main() { file := "config.json" vmName := "default" fmt.Println("***** CLI Tool *****") externUtil := externalhub.StartChecks(file, vmName) if !externUtil { fmt.Println("Sorry Check your config file, and Docker") ...
package validator import "testing" func TestValidator(t *testing.T) { Setup() data1 := "zoujh99@qq.com" data2 := "qq.com" data3 := "1234" if msg, ok := E(V().Var(data1, "required,email")); !ok { t.Log(msg) } if msg, ok := E(V().Var(data2, "required,email")); !ok { t.Log(msg) } if msg, ok := E(V().Var(dat...
// Copyright 2021 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package ch19 func validUtf8(data []int) bool { count := 0 for _, c := range data { if count == 0 { if c>>5 == 0b110 { count = 1 } else if c>>4 == 0b1110 { count = 2 } else if c>>3 == 0b11110 { count = 3 } else if c>>7 == 1 { return false } } else { if c>>6 != 0b10 { return ...
package util import ( "encoding/json" "k8s.io/klog" ) func MergeValues(dest map[string]interface{}, src map[string]interface{}, deleteKey bool) map[string]interface{} { for k, v := range src { if deleteKey && v == nil{ delete(dest, k) continue } // If the key doesn't exist already, then just set the k...
package auth import ( "context" "crypto/tls" "crypto/x509" "io/ioutil" "net" envoy_service_auth_v2 "github.com/envoyproxy/go-control-plane/envoy/service/auth/v2" envoy_service_auth_v3 "github.com/envoyproxy/go-control-plane/envoy/service/auth/v3" "google.golang.org/grpc" "google.golang.org/grpc/credentials" ...
package handler import ( "net/http" "net/http/httptest" "testing" "gopkg.in/mgo.v2" "github.com/labstack/echo" "github.com/stretchr/testify/assert" ) func TestFetchOwnTweets (t *testing.T) { session, err := mgo.Dial("mongodb://SEavenger:SEavenger@ds149324.mlab.com:49324/se_avengers") if err != nil { panic(e...
package ghttp import ( "bytes" "io/ioutil" // "log" "net/http" "net/url" "net/http/cookiejar" "crypto/tls" "encoding/json" ) var gCurCookies []*http.Cookie var gCurCookieJar *cookiejar.Jar var gInsecure bool func gInit() { gCurCookies = nil //va...
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. // package store import ( "database/sql" sq "github.com/Masterminds/squirrel" "github.com/mattermost/mattermost-cloud/model" "github.com/pkg/errors" ) var clusterInstallationSelect sq.SelectBuilder f...
// Copyright 2019 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package consulmq import ( "io/ioutil" "os" "testing" "github.com/google/uuid" "gopkg.in/yaml.v2" ) var config Config var mq *MQ func TestMain(m *testing.M) { b, err := ioutil.ReadFile("testdata/test.config") if err != nil { panic(err) } err = yaml.Unmarshal(b, &config) if err != nil { panic(err) } m...
// Copyright 2017 Attic Labs, Inc. All rights reserved. // Licensed under the Apache License, version 2.0: // http://www.apache.org/licenses/LICENSE-2.0 package main import ( "context" "encoding/base64" "github.com/attic-labs/noms/go/d" "github.com/attic-labs/noms/go/datas" "github.com/attic-labs/noms/go/hash" ...
// This file was generated by counterfeiter package fakes import ( "net/url" "sync" "github.com/cloudfoundry-incubator/garden-shed/layercake" "github.com/cloudfoundry-incubator/garden-shed/repository_fetcher" ) type FakeRepositoryFetcher struct { FetchStub func(u *url.URL, diskQuota int64) (*repository_f...
package mock import ( "filestore" "fmt" log "github.com/sirupsen/logrus" ) type mockStore struct { maxFileSize int files map[string][]byte } func NewFilestore(maxFileSize int) filestore.Store { return mockStore{ maxFileSize: maxFileSize, files: map[string][]byte{}, } } func (s mockStore) Sto...
package main import "math" //209. 长度最小的子数组 //给定一个含有n个正整数的数组和一个正整数s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组,并返回其长度。如果不存在符合条件的连续子数组,返回 0。 // //示例: // //输入: s = 7, nums = [2,3,1,2,4,3] //输出: 2 //解释: 子数组[4,3]是该条件下的长度最小的连续子数组。 //进阶: // //如果你已经完成了O(n) 时间复杂度的解法, 请尝试O(n log n) 时间复杂度的解法。 func minSubArrayLen(s int, nums []int) int { n :...
// Copyright 2020 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package users import ( "testing" "time" "github.com/jrapoport/gothic/core/tokens" "github.com/jrapoport/gothic/models/types" "github.com/jrapoport/gothic/models/types/key" "github.com/jrapoport/gothic/models/types/provider" "github.com/jrapoport/gothic/models/user" "github.com/jrapoport/gothic/test/tconn" "g...
package generator import ( "fmt" "strconv" "bytes" ) type RessourceKV struct { Champs []ChampKV } type ChampKV struct { Clef string Int int Float float64 String string Bool bool Bint bool Bfloat bool Bstring bool Bbool bool } func (ress RessourceKV) MarshalJSON() ([]byte, error) { buffer :=...
package datastore import ( "context" "math" "github.com/jackc/pgx/v4" "github.com/jackc/pgx/v4/pgxpool" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "ykjam/doc-registry-go/config" ) type PgAccess struct { Access, pool *pgxpool.Pool } func newVersion(currentVersion int) (newVersion int) { if c...
package cmd import ( "fmt" homedir "github.com/mitchellh/go-homedir" "github.com/spf13/cobra" "github.com/spf13/viper" "os" ) var cfgFile string var rootCmd = &cobra.Command{ Use: "client", Short: "BitMaelum mail client", Long: `This is the default mail client for the BitMaelum system. It is used simply a...
package generator import ( "strings" "github.com/google/gonids" ) // GenerateIPTrafficRule generates Suricata rules that alerts on inbound/outbound traffic from a IP/CIDR func (r RuleOpts) GenerateIPTrafficRule(nets []string) ([]gonids.Rule, error) { var ( err error rule gonids.Rule ) // initialize the ru...
package mymath import "testing" func TestProduct(t *testing.T) { type test struct { data []int answer int } tests := []test{ test{[]int{5, 8}, 40}, test{[]int{-2, -4, -10}, -80}, test{[]int{2, -2}, -4}, } for _, test := range tests { x := Product(test.data...) if x != test.answer { t.Errorf...
package projectmanagement import ( "log" "alauda.io/devops-apiserver/pkg/apis/devops/v1alpha1" devopsclient "alauda.io/devops-apiserver/pkg/client/clientset/versioned" "alauda.io/diablo/src/backend/api" "alauda.io/diablo/src/backend/errors" "alauda.io/diablo/src/backend/resource/common" "alauda.io/diablo/src/b...
package api import ( "encoding/json" "fmt" "net/http" "strings" ) /* BasePath is the root endpoint IDPath The path to get webhook by id LatestPath path to get latest exchange rates AveragePath path to get average exchange rates EvaluationTriggerPath to trigger all webhooks */ const ( BasePath =...
package requests import ( "fmt" "net/url" "strings" "github.com/atomicjolt/canvasapi" ) // GroupActivityStreamSummary Returns a summary of the current user's group-specific activity stream. // // For full documentation, see the API documentation for the user activity // stream summary, in the user api. // https:...
package main import ( "net/http" "log" ) func WriteByte(body string) []byte { return []byte(body) } func handle(resp http.ResponseWriter, req *http.Request) { // 解析参数,默认不解析 req.ParseForm() usernameArr := req.Form["username"] passwordArr := req.Form["password"] if len(usernameArr) <= 0 || len(passwordArr) <= ...
package main //859. 亲密字符串 //给你两个字符串 s 和 goal ,只要我们可以通过交换 s 中的两个字母得到与 goal 相等的结果,就返回true;否则返回 false 。 // //交换字母的定义是:取两个下标 i 和 j (下标从 0 开始)且满足 i != j ,接着交换 s[i] 和 s[j] 处的字符。 // //例如,在 "abcd" 中交换下标 0 和下标 2 的元素可以生成 "cbad" 。 // // //示例 1: // //输入:s = "ab", goal = "ba" //输出:true //解释:你可以交换 s[0] = 'a' 和 s[1] = 'b' 生成 "ba",此时...
package models type Wallet struct { ID int `gorm:"primary_key" json:"id"` Address string `json:"address"` Outaddress string `json:"outaddress"` Starthight int64 `json:"starthight"` Current int64 `json:"current"`//当前查询到哪个块 }
package kube_svc import ( "encoding/json" "errors" "github.com/bmsandoval/kubester/bash" "github.com/bmsandoval/kubester/utils" "github.com/ktr0731/go-fuzzyfinder" ) func SelectRelease() (*string, error) { // List all released items err, out, errout := utils.ExecGetOutput(bash.HelmList()) if err != nil { re...
package research import ( "fmt" "math" "path/filepath" "github.com/Konstantin8105/CalculixRPCclient/clientCalculix" "github.com/gonum/plot" "github.com/gonum/plot/plotter" "github.com/gonum/plot/vg" ) // RC003 - research // research ratio (height/width) of FE and precision func RC003() { researchName := "RC...
// Copyright 2022 The gVisor 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 agree...
// Package rpc includes the RPC service method for pulling tasks from the Google App Engine Task Queue. // It's used to communicate between Compute Engine and App Engine. // It's based on github.com/gorilla/rpc package rpc import ( "net/http" "encoding/json" "fmt" "code.google.com/p/google-api-go-client/taskqueue...
package main import "testing" import "bytes" func TestHash(t *testing.T) { in := []byte("Hello, world!0") out := FromHex([]byte("1312af178c253f84028d480a6adc1e25e81caa44c749ec81976192e2ec934c64")) if !bytes.Equal(out, Hash(in)) { t.Errorf("Failed to correctly take hash %s, %s", in, out, Hash(in)) } } func Test...
package main import ( "time" jwtmiddleware "github.com/auth0/go-jwt-middleware" jwt "github.com/dgrijalva/jwt-go" ) // GetJWT returns a new JWT token for an authenticated user func GetJWT(userId int) (string, error) { token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ "admin": false, "uid": ...
package convoso import "github.com/sirupsen/logrus" var log *logrus.Logger var apiKEY string var listMapper map[string]int // Init initialize this package. This must be called once with a valid instance of a Config struct func Init(c Config) error { err := c.validate() if err != nil { return err } apiKEY = c....
package notification import ( "time" model "project-support-system/model/notification" ) func (notificationDao *NotificationDao) CreateNotification(idUser int, title string, content string) error { stmt, err := notificationDao.db.Prepare("INSERT INTO Notices(idNotice) VALUES(?, ?, ?, ?)") if err != nil{ return ...
package templates import ( "bytes" "fmt" "github.com/redneckbeard/gadget" "github.com/redneckbeard/gadget/env" "html/template" "strconv" "text/template/parse" ) var ( registry = make(template.FuncMap) TemplatePath = "templates" ) // AddHelper registers functions with TemplateBroker that will be availabl...
package db import ( "log" "database/sql" _ "github.com/denisenkom/go-mssqldb" ) type Item struct { Id int `json:"id"` Name string `json:"name"` Price int `json:"price"` } type Rate struct { Id int `json:"id"` Name string `json:"name"` Percentage int `json:"price"` } func OpenConnection() (*sql.DB, er...
package pipeline import "time" import "github.com/gorhill/cronexpr" type CronScheduler struct { Runs chan *Run //note: if the errors placed on this channel are not read fast enough // some error messages could become lost Errors chan error lastJobTime time.Time lookAheadTime time.Duration background...
package main import ( "context" "errors" "fmt" "io" "sync" "time" "github.com/thegrumpylion/grpcws/example/service" ) type svc struct { sync.Mutex users map[string]string session map[string]time.Time events []string } func getToken(user string) string { return user + ".AccessKey" } func (s *svc) Log...
package config type avrDefaults struct { Ide string Framework string Port string AVRBoard string Baud int DefaultTarget string AppTargetName string PkgTargetName string } var ProjectDefaults = avrDefaults{ Ide: "none", Framework: ...
package main var;
package ipzonemanager import ( "github.com/securityclippy/goblockta/logpull" "github.com/sirupsen/logrus" "encoding/json" "fmt" "bytes" "strings" "time" "github.com/pkg/errors" ) var lg = logrus.WithField("service", "IPZoneManager") type IPZoneManager struct { Manager logpull.Manager BlockZones map[string...
/* * @Descripttion: * @version: * @Author: Jie * @Date: 2021-07-30 14:55:55 * @LastEditTime: 2021-07-30 17:36:29 */ package main import ( "fmt" "log" "github.com/gin-gonic/gin" ) type UserRe struct { Name string `form:"name"` Pwd string `form:"pwd"` } type Register struct { Uid string `form:"uid"` P...
package tag import ( "errors" "regexp" ) var jsonTagRgx = regexp.MustCompile(`(?i)json:"([a-z0-9_-]+)?,?(omitempty|inline)?"`) var ErrJsonTagNotPresent = errors.New("json tag not present") var ErrJsonIgnored = errors.New("field is ignored") var ErrInvalidJsonTag = errors.New("invalid json tag") // Result from pars...
package routing import ( "testing" "github.com/gorilla/mux" "github.com/kiali/kiali/config" ) func TestDrawPathProperly(t *testing.T) { conf := new(config.Config) config.Set(conf) router := NewRouter() testRoute(router, "Root", "GET", t) } func testRoute(router *mux.Router, name string, method string, t *te...
package main import ( "fmt" ) func main() { maplist := map[int]string{1: "one", 2: "two", 3: "three"} fmt.Printf("maplist. length is: %d \n", len(maplist)) for key, value := range maplist { fmt.Printf("key:%d value:%s \n", key, value) } maplistCopy := maplist maplistCopy[1] = "i am one" fmt.Printf("mapli...
// Copyright 2020 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package listset provides operations on lists to crostini test package listset import ( "reflect" "sort" "chromiumos/tast/errors" ) // CheckListsMatch checks whether ...
package main import ( "gamesvr/controller" "gamesvr/manager" "gamesvr/session" "shared/protobuf/pb" "shared/utility/glog" ) func main() { err := manager.Init(&session.Builder{}) if err != nil { glog.Fatalf("manager init error: %v", err) } defer manager.LuaState.Close() // 监听信号 go listenSignal() // 监听R...
package middleware import ( "github.com/sirupsen/logrus" "net/http" ) type Tracer struct{} // Prints request in log func (*Tracer) Middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { logrus.Debugf("%s %s", req.Method, req.URL) ...
package zest import ( "net/http" "github.com/unrolled/render" ) // Render is a unrolled/render based JSON/XML/HTML renderer, customized to increase // the expressiveness of Zest API error rendering. type Render struct { renderer *render.Render } // NewRender returns a new instance of Render. func NewRender() *Re...
// Copyright (C)2018 by Lei Peng <pyp126@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify,...
package main // O(n) time | O(1) space // n = length of the input array func LongestPeak(array []int) int { longestPeakLength := 0 i := 1 for i < len(array)-1 { isPeak := array[i-1] < array[i] && array[i] > array[i+1] if !isPeak { i += 1 continue } leftIdx := i - 2 for leftIdx >= 0 && array[leftId...
package main import "net/http" // Route is the structure for reach route type Route struct { Name string Method string Pattern string HandlerFunc http.HandlerFunc } // Routes stores all routes in a slice type Routes []Route var routes = Routes{ Route{ "Index", "GET", "/v1", Index, }, ...
package dlink import ( // "fmt" // "os" "time" "github.com/fatih/color" "github.com/ziutek/telnet" "log" ) const timeout = 5 * time.Second type Telnet struct { connection *telnet.Conn destination string } var DEBUG bool = false func SetDebug(debug bool) { DEBUG = debug } func NewTelnet(destination stri...
package main import "fmt" func add(x int, y int) int { return x + y } func functions() { fmt.Println("[functions.go]", add(42, 13)) }
package main import ( "fmt" "os" ) func checkfile(src string) error { if _, err := os.Stat(src); os.IsNotExist(err) { fmt.Println("File Does Not Exist") } else { deletefile(src) } return nil } func deletefile(src string) error { var err = os.Remove(src) if err != nil { fmt.Printl...
package consensus import ( "testing" "time" "github.com/NebulousLabs/Sia/types" ) // TestSynchronize tests that the consensus set can successfully synchronize // to a peer. func TestSynchronize(t *testing.T) { if testing.Short() { t.SkipNow() } cst1, err := createConsensusSetTester("TestSynchronize1") if e...
package main import "fmt" /* All values are stored in memory. Every location in memory has an address. A pointer is a memory address. When to use them? Pointers allow you to share a value stored in some memory location. Use pointers when 1. you don’t want to pass around a lot of data (enterprise load) 2. you want to...
package entities //Location an entity capturing location details of the Commodity // ID: TODO // Latitude: TODO // Longitude: TODO // Country: TODO // City: TODO // Type: TODO type Location struct { ID string Latitude float32 Longitude float32 Country string City string Type string }
package hub import ( "fmt" "net" "sync" "time" "github.com/pkg/errors" "golang.org/x/net/context" "google.golang.org/grpc" "google.golang.org/grpc/reflection" "h12.io/sej" ) type ( Server struct { Addr string Timeout time.Duration // ErrChan chan error LogChan chan string g *grpc.Server ...
package server import ( "fmt" "net/http" "strings" "time" "github.com/gempir/gempbot/internal/auth" "github.com/gempir/gempbot/internal/log" ) func (a *Api) CallbackHandler(w http.ResponseWriter, r *http.Request) { code := r.URL.Query().Get("code") resp, err := a.helixClient.RequestUserAccessToken(code) if...
package router import ( "asyncMessageSystem/app/config" "asyncMessageSystem/app/middleware/web" "github.com/kataras/iris" ) func Handler(app *iris.Application){ //加载中间件 //奔溃恢复 app.Use(web.PanicHandler) //跨域 if config.Conf.Web.Debug == true{ app.Use(web.CorsHandler) } //加载路由 UrlPath(app) }
// Unless explicitly stated otherwise all files in this repository are licensed // under the Apache License Version 2.0. // This product includes software developed at Datadog (https://www.datadoghq.com/). // Copyright 2016-present Datadog, Inc. package orchestratorexplorer import ( "fmt" "testing" apicommon "git...
package main import ( _ "dev/bee-todo-app/routers" "fmt" "github.com/astaxie/beego" "github.com/astaxie/beego/orm" _ "github.com/go-sql-driver/mysql" ) func init() { // init DB err := orm.RegisterDriver("mysql", orm.DRMySQL) if err != nil { fmt.Println(err) } err = orm.RegisterDataBase( "default", "my...
package main import ( "fmt" "os" ) func main() { //panic("oh oh something wen't wrong") file, err := os.Create("/path/to/something/that/doesnt/exist") if err != nil { panic(err) } defer func() { err := file.Close() if err != nil { panic(err) } fmt.Println("defer called") }() }
// drawingAreaMousePos.go // from: github.com/hfmrow/ package main import ( "fmt" "log" "github.com/gotk3/gotk3/gdk" "github.com/gotk3/gotk3/gtk" ) var lblX, lblY *gtk.Label // Create and initialize the window func setupWindow(title string) *gtk.Window { Width, Height := 640, 480 win, err := gtk.WindowNew...
package lmproto import ( "testing" "github.com/stretchr/testify/assert" ) func TestRecvackEncodeAndDecode(t *testing.T) { packet := &RecvackPacket{ Framer: Framer{ RedDot: true, }, MessageID: 1234, MessageSeq: 2334, } codec := New() // 编码 packetBytes, err := codec.EncodePacket(packet, 1) assert...
package transport import ( "context" "net/http" "strconv" ) // 产品详情请求的参数 /product/id type ProductDetailRequest struct { ProductId int } func ProductDetailEncode(ctx context.Context, httpRequest *http.Request, requestParam interface{}) error { pdr := requestParam.(ProductDetailRequest) httpRequest.URL.Path +=...
// Copyright 2022 The gVisor 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 agree...
package metricutil import "fmt" const successStatus = staticStatuser("success") type statuser interface { Status() string } type causer interface { Cause() error } type staticStatuser string func (s staticStatuser) Status() string { return string(s) } type errorStatuser struct { err error } func (w *errorSta...
package adoppler import ( "encoding/json" "errors" "fmt" "net/http" "net/url" "text/template" "github.com/prebid/openrtb/v19/openrtb2" "github.com/prebid/prebid-server/adapters" "github.com/prebid/prebid-server/config" "github.com/prebid/prebid-server/errortypes" "github.com/prebid/prebid-server/macros" "...
package view import ( "context" "github.com/caos/zitadel/internal/errors" global_model "github.com/caos/zitadel/internal/model" proj_model "github.com/caos/zitadel/internal/project/model" "github.com/caos/zitadel/internal/project/repository/view" "github.com/caos/zitadel/internal/project/repository/view/model" ...
// Copyright 2009 The Go Authors. All rights reserved. Use of this source code // is governed by a BSD-style license that can be found in the LICENSE file. // // Modifications for the go-transport project (2018) by Erik Hollensbe; // licensed with the same license provided with golang. // +build nobuild // XXX build...
package main import ( "os" "github.com/joho/godotenv" "github.com/pmqueiroz/http-advices/routers" ) func main() { godotenv.Load() port := os.Getenv("PORT") routers.Run(&port) }
/* * @Author: jinjiaji * @Description: 极客时间go训练营,模块一作业: 我们在数据库操作的时候,比如 dao 层中当遇到一个 sql.ErrNoRows 的时候,是否应该 Wrap 这个 error,抛给上层。为什么,应该怎么做请写出代码? * @File: module2_test * @Version: 1.0.0 * @Date: 2021/7/22 下午6:36 */ package module2 import ( "database/sql" "fmt" "testing" _ "github.com/mattn/go-sqlite3" "github...
package repos import ( "github.com/Anondo/graphql-and-go/conn" "github.com/Anondo/graphql-and-go/database/models" "github.com/jinzhu/gorm" ) // OrderProductRepo ... type OrderProductRepo struct { db *conn.DB } // NewOrderProductRepo ... func NewOrderProductRepo(db *conn.DB) OrderProduct { return &OrderProductRe...
package yamlconfig import ( "fmt" "github.com/joeig/dyndns-pdns/pkg/dnsprovider" "github.com/joeig/dyndns-pdns/pkg/dnsprovider/powerdns" "github.com/joeig/dyndns-pdns/pkg/ingest" "github.com/spf13/viper" ) const ( // IngestModeGetParameter sets the ingest mode to "GET parameter". // // The IP addresses can be...
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package wifi import ( "context" "fmt" "chromiumos/tast/common/wifi/security" "chromiumos/tast/common/wifi/security/wpa" "chromiumos/tast/remote/wificell" "chromiumos/...
package blockobserver import ( "encoding/json" "fmt" "math/big" "github.com/void616/gm.mint.rpc/rpc" ) // Parse latest blockchain block ID from node notification func (o *Observer) parseEvent(evt *rpc.Event) (latest *big.Int, err error) { latest, err = nil, nil type Noti struct { Count string `json:"co...
package solutions func find132pattern(nums []int) bool { stack := make([]int, 0) max := -1 << 31 for i := len(nums) - 1; i >= 0; i-- { if nums[i] < max { return true } for len(stack) > 0 && stack[len(stack) - 1] < nums[i] { max = stack[len(stack) - 1] ...
// Copyright 2021 The LUCI 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...
/* MIT License Copyright (c) 2018 IBM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute...
package fridge const ( eventsBuffer = 1000 ) // NewEventBus creates a new EventBus func NewEventBus() *EventBus { events := make(chan *Event, eventsBuffer) eventBus := &EventBus{events: events} go func(eventBus *EventBus) { for event := range events { if eventBus.handleEvent == nil { continue } e...